With JavaScript how would I increment numbers in an array using a for loop?

安稳与你 提交于 2020-01-02 06:24:10

问题


I am trying to increment the numbers in the array

var myArray = [1, 2, 3, 4];

I try to use

for (var i = 0; i < myArray.length; i++){
     myArray[i] + 1;
}

but that doesn't seem to do anything :( please help


回答1:


You can use map() which will make it quite clean:

var arr = [1,2,3,4];
arr = arr.map(function(val){return ++val;});
console.log(arr);



回答2:


There's many possibilities to do that, you can use plus equal += like following :

for (var i = 0; i < myArray.length; i++){
    myArray[i] += 1;
}

Or simply :

for (var i = 0; i < myArray.length; i++){
    myArray[i] = myArray[i] + 1;
}

Hope this helps.


var myArray = [1, 2, 3, 4];

for (var i = 0; i < myArray.length; i++){
    myArray[i] += 1;
}

alert(myArray);



回答3:


Use the ES6 arrow function:

arr = [1, 2, 3, 4];
new_arr = arr.map(a => a+1);
console.log(new_arr);



回答4:


Assuming your array contains ordered numbers, with increment of size 1, you can also use this code:

var myArray = [1,2,3,4];

myArray.push(myArray[myArray.length - 1] + 1);
myArray.shift();

alert(myArray);



回答5:


You can use Array constructor to do this.

Using Array.from() method

For Example :

Array.from([1,2,3,4,5], x => x+x);

That's it. And You can even create empty array with length

Array.from({length:5}, (v, i) => i);



回答6:


Without Es6,

 myArray[i] =  myArray[i] + 1;
        or
   ++myArray[i]

Will work.



来源:https://stackoverflow.com/questions/32796230/with-javascript-how-would-i-increment-numbers-in-an-array-using-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!