[英]With JavaScript how would I increment numbers in an array using a for loop?
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但这似乎无济于事:(请帮忙
You can use map()
which will make it quite clean:您可以使用map()
这将使它非常干净:
var arr = [1,2,3,4]; arr = arr.map(function(val){return ++val;}); console.log(arr);
Use the ES6 arrow function:使用 ES6 箭头函数:
arr = [1, 2, 3, 4]; new_arr = arr.map(a => a+1); console.log(new_arr);
There's many possibilities to do that, you can use plus equal +=
like following :有很多可能性可以做到这一点,您可以使用 plus equal +=
,如下所示:
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);
Assuming your array contains ordered numbers, with increment of size 1, you can also use this code:假设您的数组包含有序数字,增量为 1,您还可以使用以下代码:
var myArray = [1,2,3,4]; myArray.push(myArray[myArray.length - 1] + 1); myArray.shift(); alert(myArray);
Without Es6,没有 Es6,
myArray[i] = myArray[i] + 1;
or
++myArray[i]
Will work.将工作。
You can use Array constructor to do this.您可以使用 Array 构造函数来执行此操作。
Using Array.from() method使用 Array.from() 方法
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);
You can use ES6's Array.from()
method.您可以使用 ES6 的Array.from()
方法。 The callback is a mapping function, which you can use to add one to each number in the array.回调是一个映射函数,您可以使用它为数组中的每个数字加一。
Here the prefix (rather than postfix) increment operator ++
is used in the map function because when you use the increment operator before the operand, the increment occurs before the value is returned, whereas with postfix, the original value will be returned before the operand will be increased (so, an unchanged version of the array would be returned in the case of x++
).这里在 map 函数中使用了前缀(而不是后缀)增量运算符++
,因为当您在操作数之前使用增量运算符时,增量发生在返回值之前,而使用后缀,原始值将在返回之前返回操作数将增加(因此,在x++
的情况下将返回未更改的数组版本)。
function addOne(arr) {
return Array.from(arr, x => ++x);
}
addOne([1, 2, 3]); // [2, 3, 4]
You can use Array constructor.您可以使用 Array 构造函数。
Using Array.map()
method, fill the series with numbers使用Array.map()
方法,用数字填充系列
For Example :例如 :
Array(5 + 1).fill().map((_, index) => index + 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.