简体   繁体   中英

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:

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

All I had to do was move the return outside the loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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