如何使用forEach来改变数组

时间:2017-07-09 01:31:25

标签: javascript foreach

指示forEach()对阵列进行永久性更改需要哪些代码?

例如,在下面的简单代码中,我添加了短语,"这是我的"到数组中的每个项目。根据控制台日志,进行了更改。但是当我在主时间轴上再次运行控制台时,更改并未永久保存到阵列中。我确定我错过了一些简单但我无法看到的东西。



var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

console.log(myArray);

myArray.forEach(myFunction);

function myFunction(item) {
    item = "this is my " +item;
    console.log(item);
}

console.log(myArray);




1 个答案:

答案 0 :(得分:4)

  

forEach()不会改变调用它的数组(尽管如此)   回调,如果被调用,可能会这样做。)

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

使用Map

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

const myArrayChanged = myArray.map(myFunction);

function myFunction(item) {
    return "this is my " + item;
}

console.log(myArray);
console.log(myArrayChanged);

但是,正确回答有关如何使用forEach进行操作的问题,请点击此处:

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

console.log(myArray);

myArray.forEach(myFunction);
function myFunction(item, i, arr) {
    return arr[i] = "this is my " + item;
}

console.log(myArray);