console.log shows original array after foreach

John Doe :
let words = ["[hello", "]bye", "", "lol-"];
words.forEach((item, index) => {
    item = item.replace(/\[|\]|\-/g, "");
    if (item == "") words.splice(index, 1);
});
console.log(words);

Why I always get Array(3) [ "[hello", "]bye", "lol-" ]?

I tried to console.log item after replace() and it returns correct item.

Maheer Ali :

forEach only iterates through array. If you want to change elements of array use map() and to remove the empty string use filter()

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=278937&siteId=1