3 回答

TA貢獻1801條經驗 獲得超8個贊
回調傳遞給元素,索引和數組本身。
arr.forEach(function(part, index, theArray) {
theArray[index] = "hello world";
});
編輯 —如注釋中所述,該.forEach()函數可以采用第二個參數,該參數將用作this每次對回調的調用中的值:
arr.forEach(function(part, index) {
this[index] = "hello world";
}, arr); // use arr as this
第二個示例顯示了arr自己this在回調中的設置。有人可能會認為.forEach()調用中涉及的數組可能是的默認值this,但無論出于何種原因,它都不是。this會undefined如果沒有提供第二個參數。
同樣重要的是要記住,Array原型上提供了一整套類似的實用程序,并且在Stackoverflow上彈出了有關一個或另一個功能的許多問題,因此最好的解決方案是簡單地選擇其他工具。你有:
forEach 用于處理數組中的每個條目或對數組中的每個條目執行操作;
filter 用于產生僅包含合格條目的新數組;
map 用于通過變換現有陣列來制作一對一的新陣列;
some 檢查數組中的至少一個元素是否符合某些描述;
every檢查數組中的所有條目是否與描述相匹配;
find 在數組中尋找一個值

TA貢獻1816條經驗 獲得超6個贊
數組:[1, 2, 3, 4]
結果:["foo1", "foo2", "foo3", "foo4"]
Array.prototype.map() 保留原始陣列
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);
console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
Array.prototype.forEach() 覆蓋原始數組
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);
console.log( "Overridden: %s", originalArr );
添加回答
舉報