用于循环到每个元素的数组方法

时间:2017-01-15 19:00:12

标签: javascript arrays reactjs for-loop redux

我正在编写一个redux函数,任何时候我点击一个按钮我必须在数组的第四个元素中添加一个数字n。如果元素是L或M,我不想要添加

示例我在下面有这个数组,要添加的数字,即n是'5'

[M 175 0  L 326 87 L 326]

我单击按钮一次,阵列变为

[M 175 0  L 331 87 L 326]

第四个元素变为331

我单击按钮两次,数组变为

[M 175 0  L 331 92 L 326]

第五个元素变为92

依此类推,直到数组完成,然后我再次从第三个元素开始

这是我的初始函数,其中我映射了所有值

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);

请参阅here实际操作

但是现在我需要一个其他的数组方法来实现它,但我不知道哪个以及如何

6 个答案:

答案 0 :(得分:1)

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>

如果您有任何疑问,请告诉我。只需提供帮助,我将解释

答案 1 :(得分:1)

虽然不是使用react.js而是使用纯JS,但您可以执行以下操作;

&#13;
&#13;
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));
&#13;
<button id="myButton">Add 5</button>
<p id="result"></p>
<button id="increase">Increase</button>
<button id="decrease">Decrease</button>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果我理解正确,您的问题是,从现有数组中,在遵循规则时获取一个(不一定是新的):

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

考虑实施:

function getValue (original, value) {

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

}

因此,每次触发处理程序时,您都可以更新数组,使用空格连接并渲染SVG(我想这是一个路径)。

沿着这些方向:

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);

}

如果您使用的是React,则可能需要触发重新渲染。您的组件将如下所示:

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>;

     }

}

答案 3 :(得分:1)

您可以使用Array.prototype.reduce()(Refer

reduce()方法对累加器和数组的每个值(从左到右)应用一个函数,将其减少为单个值。

var str = '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';

str.split(/\s+/).reduce((prevVal, x) => x === 'M' || x === 'L' ? prevVal + ' ' + x : prevVal + ' ' + (+x + 5));

因此,reduce是您可以使用的另一种方法。

答案 4 :(得分:0)

我建议您使用纯JS的解决方案而不做出反应

&#13;
&#13;
var string = "M 175 0 L 326 87 L 326 262 M 175 350 L 23 262 L 23 87 M 175 0";
var array = string.split(" ");
var max = array.length;
var i = 3;
var clic = () => {
      i++;
      if (i === max) i = 3;
      if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5;
      console.log(array.join(' '));
};
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();
clic(); clic(); clic(); clic(); clic(); clic();
&#13;
&#13;
&#13;

答案 5 :(得分:0)

使用此:

let string = state[a].d
let array = string.split(/\s+/)
var n=5;
var finalArray=array.map(function(current, index) {
   if (current=="L" || current=="M") {
     return current;
   }else{
    return new Number(current)+n*4-n*(3-Math.min(index,3));
   }

});

它为您提供了完成从索引3(元素4)到0完成整个过程后的最终数组。