如何从数组中的每个数字中减去1? [重复]

时间:2021-12-21 01:17:05

This question already has an answer here:

这个问题在这里已有答案:

If I have

如果我有

var numberarr = [1, 2, 3, 4, 5];

How would i make it into

我将如何进入

var numberarr2 = [0, 1, 2, 3, 4];

by decrementing 1 from each element?

通过从每个元素递减1?

2 个解决方案

#1


22  

You can use .map( )

你可以使用.map()

var numberarr2 = numberarr.map( function(value) { 
    return value - 1; 
} );

#2


2  

Try this:

尝试这个:

// Create an array to hold our new values
var numberArr2 = [];

// Iterate through each element in the original array
for(var i = 0; i < numberArr1.length; i++) {

    // Decrement the value of the original array and push it to the new one
    numberArr2.push(numberArr1[i] - 1);
}

#1


22  

You can use .map( )

你可以使用.map()

var numberarr2 = numberarr.map( function(value) { 
    return value - 1; 
} );

#2


2  

Try this:

尝试这个:

// Create an array to hold our new values
var numberArr2 = [];

// Iterate through each element in the original array
for(var i = 0; i < numberArr1.length; i++) {

    // Decrement the value of the original array and push it to the new one
    numberArr2.push(numberArr1[i] - 1);
}