简体   繁体   中英

When defining a key:value pair structure when object literal is prefered over array definition?

Suppose I want to define a structure which holds different key:value combinations. When I would prefer first over second?

hashMap = [ ] 

hashMap["first"] = 1

object = { first : 1 }

object["first"] == hashMap["first"] // so they are the same basically

Always. Arrays are for ordered lists of values. Although they happen to inherit from Object.prototype , no one will be expecting an array to have values outside of its number indicies (in most cases) - it will be a prime source of confusion. That's not what arrays are for.

If you want a collection of key-value pairs, always prefer an ordinary object over an array. Objects are for collections of key-value pairs. Arrays are for ordered collections of values only.

Always use objects for non-numeric key collections. That has various reasons:

(1) Arrays are optimized for numeric key access, thus using non-numeric keys will be slower. Objects are designed to be arbitrary key-value stores.

(2) Serialization removes all non-numeric keys from arrays:

const arr = [];
arr.key = "test";
console.log(JSON.parse(JSON.stringify(arr))); // []

(3) Array's properties and methods might confuse you:

  • .length only counts numeric keys.

  • .map , .forEach , ... will only iterate over numeric keys.

  • for..of will only iterate over numeric keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM