Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Método de matriz para hacer un bucle en cada elemento

Estoy escribiendo una función redux donde cada vez que hago clic en un botón tengo que agregar un número n al cuarto elemento de la matriz. Si el elemento es L o M no quiero la adición

Ejemplo: tengo esta matriz a continuación y el número para agregar, es decir, n es '5'

 [M 175 0 L 326 87 L 326]

Hago clic en el botón una vez y la matriz se convierte en

 [M 175 0 L 331 87 L 326]

El cuarto elemento se convierte en 331

Hago clic en el botón dos veces y la matriz se convierte en

 [M 175 0 L 331 92 L 326]

El quinto elemento se convierte en 92

Y así sucesivamente hasta que la matriz termine y empiezo de nuevo desde el tercer elemento.

Esta es mi función inicial donde estaba mapeando todos los valores

 var string = 'M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0', array = string.split(/\s+/), result = array.map(x => x === 'M' || x === 'L' ? x : +x + 5).join(' '); console.log(result);

Veraquí en acción

pero ahora necesito otro método de matriz para lograrlo, pero no sé cuál y cómo

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

 let clicks = 0; class App extends React.Component { state= {data:'M 175 0 L 326 87 L 326'}; onClick() { clicks ++; this.setState({data: this.increment()}); } /** * clicks -> Element index in array * 1 ----- ->4, * 2 ---- -> 5. * 3 ---- -> 7. * 4 ----- ->4, * 5 ---- -> 5. * 6 ---- -> 7. */ increment() { const data = this.state.data.replace(/\ \ /g, " ").split(" "); const indexAlteredElement = (clicksModulo) => (! clicksModulo % 3) ? 7 : clicksModulo+3; return data.map((e, i) => (i === indexAlteredElement(clicks%3)) ? parseInt(e)+5 : e ).join(' ') } render() { return ( <div> <div>{this.state.data} </div> <button onClick={this.onClick.bind(this)} style={{fontSize:20}}> Click me </button> </div> ) } } ReactDOM.render(<App />, document.querySelector('.container'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <section class="container"></section>

Avíseme si tiene alguna pregunta ... solo dé la línea y le explicaré

over 4 years ago · Santiago Trujillo Report

0

Si bien no es por react.js sino por JS puro, puede hacer lo siguiente;

 function ClickHandler(s){ this.cct = 3; // click count this.str = s; // the string this.num = 5; // increase amount this.but = null; // the add button element this.res = null; // the result paragraph element } ClickHandler.prototype.insert = function(){ var a = this.str.split(/\s+/); this.str = a[this.cct] === "L" || a[this.cct] === "M" ? a.join(" ") : (a[this.cct] = (+a[this.cct] + this.num) + "", a.join(" ")); this.cct = (this.cct+1)%a.length || 3; }; ClickHandler.prototype.increase = function(){ this.but.textContent = this.but.textContent.replace(/-?\d+/,++this.num); }; ClickHandler.prototype.decrease = function(){ this.but.textContent = this.but.textContent.replace(/-?\d+/,--this.num); }; var string = "M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0", whenClicked = new ClickHandler(string), increase = document.getElementById("increase"), decrease = document.getElementById("decrease"); whenClicked.but = document.getElementById("myButton"); whenClicked.res = document.getElementById("result"); whenClicked.res.textContent = string; whenClicked.but.addEventListener("click", function(e){ this.insert(); this.res.textContent = this.str; }.bind(whenClicked)); increase.addEventListener("click", whenClicked.increase.bind(whenClicked)); decrease.addEventListener("click", whenClicked.decrease.bind(whenClicked));
 <button id="myButton">Add 5</button> <p id="result"></p> <button id="increase">Increase</button> <button id="decrease">Decrease</button>

over 4 years ago · Santiago Trujillo Report

0

Su problema es, si entiendo correctamente, de una matriz existente, obtenga uno (no necesariamente nuevo) mientras sigue la regla:

 If the current value is M or L do nothing, return the value, else consider it a number, add 5 to it and return.

Considere la implementación:

 function getValue (original, value) { return original === "M" || original === "L" ? original : parseFloat(original, 10) + value; }

Entonces, cada vez que se activa su controlador, puede actualizar su matriz, unirla con espacios en blanco y representar su SVG (supongo que esta es una ruta).

Algo por el estilo:

 const array = // your array const index = 5; function onClick () { // you need to attach this handler to whatever node / object you are listening to array[index] = getValue(array[index], 5); }

Si está utilizando React, es posible que desee activar una nueva representación. Su componente se verá así:

 class C extends React.Component { constructor (props) { super(props); this.state = { array: .... } // the state is initialized with your array } render () { return <div> {/*anything you want*/} <button onClick={() => this.setState({ array: [...this.state.array.slice(4), getValue(this.state.array[4], 5), ...this.state.array.slice(5)] })}>Click me</button> </div>; } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!