在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ JavaScript數(shù)組map方法的疑問[已解決]

JavaScript數(shù)組map方法的疑問[已解決]

問題
一個長度為4空數(shù)組
map()給數(shù)組元素賦值
為什么新數(shù)組還是空的呢?

下面的代碼為什么不輸出
[empty × 4]    [2,2,2,2]

代碼

var array = new Array(4);
var newArray = array.map(item=>{
    return '2'
});
console.log(array,newArray);
// =>[empty × 4]   [empty × 4]

解決

普通方法無法遍歷稀疏數(shù)組,只能用1樓所說的特殊方法才能遍歷
回答
編輯回答
短嘆

Array.map的callback只會針對已經(jīng)賦值過的item進(jìn)行調(diào)用(包括undefined)。
所以當(dāng)有的元素被刪除了,或者從來沒有被賦值的時候,callback不會調(diào)用這個元素。

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).
2017年12月12日 06:21
編輯回答
哚蕾咪

clipboard.png

JavaScript權(quán)威指南-第六版-中p157,說白了,空項會自動跳過,返回空項,如果賦值了 undefined 不會跳過

2017年3月19日 10:58
編輯回答
夢一場

什么都沒有的數(shù)組元素叫做槽(slot),一般方法都會忽略,可以用 Array.prototype.fill、Array.from 或者 [...arr] 的方式轉(zhuǎn)換。

比如 Array.from(new Array(4))

2017年7月10日 08:18
編輯回答
小曖昧

這個你需要通過閱讀V8引擎的源代碼來獲取答案:

function ArrayMap(f, receiver) {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");

  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = TO_OBJECT(this);
  var length = TO_LENGTH(array.length);
  if (!IS_CALLABLE(f)) throw %make_type_error(kCalledNonCallable, f);
  var result = ArraySpeciesCreate(array, length);
  for (var i = 0; i < length; i++) {
    if (i in array) {
      var element = array[i];
      %CreateDataProperty(result, i, %_Call(f, receiver, element, i, array));
    }
  }
  return result;
}

在這里,我們注意到,它首先是用了一個TO_OBJECT來把數(shù)組轉(zhuǎn)為了對象,然后用了一個for循環(huán)在對象中查找下標(biāo),也就是這一句話:if (i in array),而當(dāng)我們用new Array(4)來創(chuàng)建數(shù)組時,實際創(chuàng)建的只是一個指針,并沒有創(chuàng)建實體的4個元素,所以當(dāng)它被轉(zhuǎn)化為對象時,得到是{}這樣的空對象,所以這里的每一個if語句分枝都不會被執(zhí)行。

但如果我們用var array = [null, null, null, null]或者哪怕array = [undefined, undefined, undefined, undefined]來做,效果都會大不一樣,因為以這樣方式創(chuàng)建的數(shù)組,轉(zhuǎn)化為的對象是:

{
  0: undefined,
  1: undefined,
  2: undefined,
  3: undefined,
}

當(dāng)對這樣的對象進(jìn)行if (i in array)操作時,可以找到相應(yīng)的下標(biāo),所以可以依次執(zhí)行。這就是根本原因。

2017年6月22日 16:57
編輯回答
維她命

這應(yīng)該和map函數(shù)邏輯有關(guān)系,使用你的代碼我發(fā)現(xiàn)map函數(shù)并有遍歷四次,其實一次都沒遍歷。具體的問題需要看看map內(nèi)部實現(xiàn)才曉得了

2017年1月25日 05:51