總結回顧html
昨天在看一道筆試題的時候本覺得很簡單,可是結果不是我想象的那樣,直接上筆試題。前端
const array = new Array(5).map((item) => {
return item = {
name: '1'
}
});
console.log(array);
// 請寫出輸出結果
複製代碼
我想象的答案:[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}]; 面試
實際的答案:[empty × 5] 數組
爲何會這樣了?bash
我第一個想到的是new Array(5)生成的數組是[undefined, undefined, undefined, undefined, undefined]。網絡
const array = [undefined, undefined, undefined, undefined, undefined];
const newArr = array.map((item) => {
return item = {
name: '1'
}
});
console.log(newArr);
// 結果是[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
複製代碼
猜測1錯誤閉包
new Array(5)生成的數組在每一項都沒有值,意思就是生成了[,,,,,]一個這樣的數組。app
const array = [,,,,,];
const newArr = array.map((item) => {
return item = {
name: '1'
}
});
console.log(newArr);
// 結果是[empty × 5];
複製代碼
猜測2正確(這裏大喊本身牛逼)ide
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined).函數
It is not called for missing elements of the array; that is:
map依次爲數組中的每一個元素調用一次提供的callback函數,而後根據結果構造一個新的數組。-----僅對已分配值(包括)的數組索引進行調用----。 map函數的回調函數只會被賦過值的項調用。new Array(1) 和 [undefined]不同。new Array(1)沒有爲數組中的項賦過值,而[undefined]爲數組中的項賦了一個undefined值。
// 處理1
const array = new Array(5).fill().map((item) => {
return item = {
name: '1'
}
});
console.log(array);
// [{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
// 處理2
var array = Array.apply(0,{length:5}).map((item) => {
return item = {
name: '1'
}
});
console.log(array);
// [{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
複製代碼