发布于 2026-01-05 1 阅读
0

不要到处使用 Array.map() 🥵

不要到处使用 Array.map() 🥵

大多数时候我看到的片段是这样的👇



const fruits = ["apple", "orange", "cherry"];
let text = "";
document.getElementById("main").innerHTML = text;
fruits.map(i => text += i );


Enter fullscreen mode Exit fullscreen mode

在上面的代码片段中,我们fruits向 DOM 中添加了mainID 为 的文本。
虽然上面的代码片段看起来没有问题,但实际上存在一个主要问题,我们今天将要探讨这个问题。

让我们通过定义来理解这个问题mapmap()该方法创建一个新数组,其中包含对调用数组中的每个元素调用提供的函数的结果。

例子:



let n = [1, 2, 3, 4];
let add = n.map(i => i + 2);
console.log(add); // [3, 4, 5, 6]


Enter fullscreen mode Exit fullscreen mode

注意:使用map()该方法意味着返回一个新的数组集合。

如前所述,map()该方法总是返回一个新数组,因此如果您不需要新数组,则永远不要使用map()此方法。
当您只需要遍历数组时,我始终建议使用其他数组方法,例如 ` forEachmap` 或 `get` for..of

例子:



const fruits = ["apple", "orange", "cherry"];
let text = "";
fruits.forEach(myFunction);

document.getElementById("main").innerHTML = text;

function myFunction(item, index) {
text += index + ": " + item + "<br>";
}

Enter fullscreen mode Exit fullscreen mode




我们为什么要关心这件事?🙄

我们知道,map()该方法总是返回一个数组。如果只是需要更新 DOM,那么将这些元素存储到内存中没有任何意义。
当然,对于少量数字,不会产生任何影响;但是,如果数字较大,则会影响性能,因为它会将冗余值存储在内存中。

摘要⅀

map()如果只是需要遍历数组,请停止使用该方法。如果需要遍历数组,
请开始使用forEach或方法。for...of

感谢阅读本文❤️
希望这篇文章对您有所帮助!

请我喝杯咖啡

🌟推特 📚电子书 🌟 Instagram
文章来源:https://dev.to/suprabhasupi/stop-using-arraymap-everywhere-57lf