使用 JavaScript 如何使用 for 循环递增数组中的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32796230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:13:04  来源:igfitidea点击:

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

javascriptarraysfor-loop

提问by lateralus500

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

但这似乎没有任何作用:(请帮忙

回答by baao

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

您可以使用map()which 将使其非常干净:

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

回答by Zakaria Acharki

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

回答by Julian Gong

Use the ES6 arrow function:

使用 ES6 箭头函数:

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

回答by xxxmatko

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

回答by thangavel .R

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

回答by chelladurai89

Without Es6,

如果没有 Es6,

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

Will work.

将工作。