【问题标题】:Array Method for looping to each element循环到每个元素的数组方法
【发布时间】:2017-05-30 14:58:36
【问题描述】:

我正在编写一个 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 的实际操作

但现在我需要其他数组方法来实现这一点,但我不知道哪种方法和方法

【问题讨论】:

  • 请不要使用string作为变量,容易与全局String混淆。
  • 它总是在第一个L之后的第一个和第二个元素吗?
  • 请添加您想要更改的元素以及输入字符串的外观和想要的输出。什么是“等等,直到数组完成并且我从第三个元素重新开始”?只有'L' 部分/秒?

标签: javascript arrays reactjs for-loop redux


【解决方案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>

如果您有任何问题,请告诉我.. 只需打个电话,我会解释

【讨论】:

  • 我会接受答案,但如果你能在我的场景中为我展示如何做到这一点,那就更清楚了。我在这里告诉你gist.github.com/Mannaio/35f50c0ecc71f6e35ca6f918fadec492
  • Sagar Shetty 的答案显示了我需要的数组方法,但它没有达到我想要的结果。如果您的演示是正确的,则该答案是正确的
【解决方案2】:

我建议你一个纯 JS 的解决方案,没有反应

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

【讨论】:

    【解决方案3】:

    虽然不是通过 react.js 而是纯 JS 你可以这样做;

    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>

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        你可以使用 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 是您可以使用的另一种方法。

        【讨论】:

        • 这是我需要的数组方法,但这里唯一的问题是每次点击时将 5 与所有数字相加,我需要从第四个元素和仅对 i 数字求和 '5' .查看 Abdennour TOUMI 演示
        【解决方案6】:

        使用这个:

        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 的整个过程运行后得到的最终数组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-21
          • 1970-01-01
          • 1970-01-01
          • 2021-08-24
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          相关资源
          最近更新 更多