console.log在foreach之后显示原始数组

时间:2020-03-14 15:54:22

标签: javascript

import mypackage_commithash1 as p1
import mypackage_commithash2 as p2

results1 = p1.do_something()
results2 = p2.do_something()

plot_comparison(results1, results2)

为什么我总是得到let words = ["[hello", "]bye", "", "lol-"]; words.forEach((item, index) => { item = item.replace(/\[|\]|\-/g, ""); if (item == "") words.splice(index, 1); }); console.log(words);

我在Array(3) [ "[hello", "]bye", "lol-" ]之后尝试console.log的商品,它返回了正确的商品。

3 个答案:

答案 0 :(得分:4)

forEach仅遍历数组。如果要更改数组元素,请使用map(),并删除空字符串,请使用filter()

let words = ["[hello", "]bye", "", "lol-"];
words = words.map((item, index) => item.replace(/\[|\]|\-/g, "")).filter(x => x !== '');
console.log(words);

答案 1 :(得分:1)

您只需要使用forEach的第三个参数来获取源数组:

let words = ["[hello", "]by--e", "", "lol--"];
words.forEach((item, index, arr) => {
    arr[index] = item.replace(/\[|\]|\-/g, "");
});
words = words.filter(item => item);
console.log(words);

答案 2 :(得分:0)

forEach方法不会修改实际的数组。您应该使用mapfilter方法来实现结果。

let words = ["[hello", "]bye", "", "lol-"];
let updatedWords = words.map((item, index) => {
    item = item.replace(/\[|\]|\-/g, "");
    return item;
});

updatedWords = updatedWords.filter(word => word !== "");
console.log(updatedWords);
相关问题