這道JS筆試題你作對了嗎?

總結回顧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

猜測1

我第一個想到的是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錯誤閉包

猜測2

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:

  • indexes that have never been set;
  • which have been deleted; or
  • which have never been assigned a value.

map依次爲數組中的每一個元素調用一次提供的callback函數,而後根據結果構造一個新的數組。-----僅對已分配值(包括)的數組索引進行調用----。 map函數的回調函數只會被賦過值的項調用。new Array(1) 和 [undefined]不同。new Array(1)沒有爲數組中的項賦過值,而[undefined]爲數組中的項賦了一個undefined值。

總結

  • new Array(5)產生的數組是一個沒有爲數組中的項賦過值的數組。
  • map僅對已分配值(包括)的數組索引進行callback調用。

優化處理

// 處理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'}];
複製代碼
相關文章
相關標籤/搜索