[英]Deleting JSON object inside an array, when the object has key value pair where the value is ""
[英]When defining a key:value pair structure when object literal is prefered over array definition?
假設我想定義一個包含不同鍵:值組合的結構。 什么時候我更喜歡第一而不是第二?
hashMap = [ ]
hashMap["first"] = 1
object = { first : 1 }
object["first"] == hashMap["first"] // so they are the same basically
總是。 Arrays 用於有序的值列表。 盡管它們碰巧繼承自Object.prototype
,但沒有人會期望數組的值超出其數字索引(在大多數情況下)——這將是混淆的主要來源。 這不是 arrays 的用途。
如果你想要一個鍵值對的集合,總是更喜歡普通的 object 而不是數組。 對象用於鍵值對的 collections。 Arrays 僅用於訂購的 collections 值。
始終為非數字鍵 collections 使用對象。 這有多種原因:
(1) Arrays 針對數字鍵訪問進行了優化,因此使用非數字鍵會更慢。 對象被設計為任意鍵值存儲。
(2) 序列化從 arrays 中刪除所有非數字鍵:
const arr = [];
arr.key = "test";
console.log(JSON.parse(JSON.stringify(arr))); // []
(3) Array 的屬性和方法可能會讓你感到困惑:
.length
只計算數字鍵。
.map
, .forEach
, ... 只會遍歷數字鍵。
for..of
只會遍歷數字鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.