簡體   English   中英

使用 JavaScript,如何增加數組中的所有項目並返回數組?

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

我堅持使用一個函數遞增數組中的所有項目並返回數組。 現在要做什么?

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

您可以簡單地將Array.prototype.map與箭頭函數一起使用:

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

你的嘗試很棒,但你的return arr; 太早了。 請注意,您也在修改數組,而不是返回帶有更新值的副本。 你可以先用arr = [...arr];復制數組arr = [...arr]; .

我所要做的就是將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