簡體   English   中英

JavaScript:Array.push() 與文字(括號)表示法

[英]JavaScript: Array.push() vs. Literal (Bracket) Notation

我指的是這個答案

為什么Code Snippet 2 的返回值與Code Snippet 1 不同

代碼片段 1:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return ar;
}, []);

代碼片段 2:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar['eventTitle'] = e.getTitle();
    ar['eventId'] = id;
    ar['startDate'] = e.getAllDayStartDate();
    ar['endDate'] = e.getAllDayEndDate();
  }
  return ar;
}, []);

編輯:

為什么代碼片段 3 的行為符合預期(每個事件系列添加一個對象)而代碼片段 4則不然?

代碼片段 3:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id});
  }
  return ar;
}, []);

代碼片段 4:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle()});
  }
  return ar;
}, []);

ar.push({/*...*/})創建一個對象並將該對象推送到數組中。

ar['eventTitle'] = e.getTitle(); 並使用這些名稱在數組上創建屬性(每次都覆蓋以前的值)。 他們不會將條目放入數組中。

如果您的目標是將對象放入數組,則帶有push的版本是正確的。

在數組上擁有任意屬性似乎很奇怪,但標准數組是對象,因此您可以向它們添加屬性。

如果你想通過賦值添加到數組中,你可以這樣做:

ar[ar.length] = {eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()};

這就是push作用。

在第一個示例中,reduce 函數將數據推送到聚合數組中。

ar.push({...})

在第二個示例中,聚合將數組上的值設置為鍵, arrays === objects JS 中的arrays === objects

ar['key-name'] = whatever

第一個示例代碼使用 push,即向數組 ar 添加一個對象。

使用括號表示法的第二個示例代碼,它正在更改對象 ar 中的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM