简体   繁体   English

使用 JavaScript,如何增加数组中的所有项目并返回数组?

[英]Using JavaScript, how can I increment all items in an array and return the array?

There is one function that I am stuck on with incrementing all of the items in my array and returning the array.我坚持使用一个函数递增数组中的所有项目并返回数组。 What to do now?现在要做什么?

function incrementByOne(arr) {
  // arr is an array of integers(numbers), Increment all items in the array by
  // return the array
  for (let i = 0; i < arr.length; i++) {
    arr[i] += 1;
    return(arr);
  }
 
}

You can simply use Array.prototype.map with an arrow function for this:您可以简单地将Array.prototype.map与箭头函数一起使用:

 function incrementByOne(arr) { return arr.map(value => value + 1); } console.log(incrementByOne([1,5,4,7,3]));

Your attempt was great, but your return arr;你的尝试很棒,但你的return arr; is too early.太早了。 Mind that you're also modifying the array, instead of returning a copy with updated values.请注意,您也在修改数组,而不是返回带有更新值的副本。 You could copy the array first with arr = [...arr];你可以先用arr = [...arr];复制数组arr = [...arr]; . .

All I had to do was move the return outside the loop.我所要做的就是将return移到循环之外。

function incrementByOne(arr) {
      // arr is an array of integers(numbers), Increment all items in the array by
      // return the array
      for (let i = 0; i < arr.length; i++) {
        arr[i] += 1;
      }
      return(arr);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM