简体   繁体   中英

JS foreach loop to update an array element

I am currently learning JavaScript. And I tried to use a foreach loop to update my elements in an array. But the problem is that the "console.log" result always been the same array as before. Below is the code. Can anyone help tell the problem?

var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
    19, 300, 3775, 299, 36, 209, 148, 169, 299,
    6, 109, 20, 58, 139, 59, 3, 1, 139
];

var addNum = function(element,index,array){
    if(element%3===0)
    {
        element += 100;
    }
};

test.forEach(addNum);
console.log(test);

That's because in JavaScript arguments are passed by value, not by reference.
So changing element argument does nothing.

In your case, it is better to use map , like this:

var addNum = function(element,index,array){
    if(element%3===0)
    {
        return element + 100;
    }

    return element
};

const result = test.map(addNum);
console.log(result);

If you really need to use forEach - you could do it like this:

var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
    19, 300, 3775, 299, 36, 209, 148, 169, 299,
    6, 109, 20, 58, 139, 59, 3, 1, 139
];

var addNum = function(element,index,array){
    if(element%3===0)
    {
        array[index] += 100;
    }
};

test.forEach(addNum);
console.log(test);

But this is, in my opinion, a bad practice.
forEach is designed for doing something with each element in an array without changing it, but map is specifically designed to create new array running a function on each element of the provided array.
Also see discussion here Is there a difference between foreach and map?

In your addNum function, element is just an argument. When you modify it , you are only modifying the value inside the function, not the actual element in the array.

To modify the array, you need to target the element:

 var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139 ]; var addNum = function(element, index, array) { if (element % 3 === 0) { array[index] = element + 100; } }; test.forEach(addNum); console.log(test); 

Note that in JavaScript you can directly pass an anonymous function to forEach() :

test.forEach(function(element, index, array) {
    if (element % 3 === 0) {
        array[index] = element + 100;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM