问题
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