簡體   English   中英

JavaScript 數組索引

[英]JavaScript array indexes

我正在使用 Angular1x,我只想創建一個帶有數字索引的數組對象:

var unreadMessagesCookieObject = [];

unreadMessagesCookieObject[id] = {
     id: messageObj.id,
     lastNotified: moment.getTime()
};

一切都好嗎? 好吧,不是真的:

(6) [null, null, null, null, null, {…}]
0: null
1: null
2: null
3: null
4: null
5:
id: 1
lastNotified: 1601769147988

為什么我有一個帶有 5 個null索引的對象。 我想將對象寫入 cookie 而不是 5 個空值。

如何創建具有任意數字索引的數組對象。 請注意,我不能使用 0 作為我的第一個索引,因為我希望能夠通過 id 在數組對象中進行搜索。

JS 數組已經是類似列表的對象。 我不是試圖覆蓋它的行為,而是告訴你創建一個標准的 JS 對象。

let unreadMessagesCookieObject = Object.create(null);

unreadMessagesCookieObject[id] = {
   id: messageObj.id,
   lastNotified: moment.getTime()
};

工作片段:

 let unreadMessagesCookieObject = Object.create(null); unreadMessagesCookieObject[5] = { id: 1, lastNotified: 1601769147988 }; console.log(unreadMessagesCookieObject);

暫無
暫無

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

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