+ 2
Why JavaScript does not support arrays with named indexes?
I didn’t understand on the lesson!
3 Antworten
+ 5
JavaScript allows for named indexes (known as "keys"), they're known as JavaScript Objects. You can create an object like this:
let fruitPrices = {
"apples": 3,
"oranges": 2,
"watermelons": 4
}
You can access members of an object using the dot operator or the array-access operator. Ex:
let applePrice = fruitPrices.apples
let watermelonPrice = fruitPrices["watermelons"]
console.log(applePrice)
console.log(watermelonPrice)
/* outputs:
>3
>4
*/
The dot operator method is useful for writing quick code, but using the array-access operator is more versatile, since it allows you to use variables to access elements. For example:
let str = "oranges"
console.log(fruitPrices[str])
//output: 2
let str = "oranges"
console.log(fruitPrices.str)
//output: null
In the second example, the code thinks that we are trying to access a member of the fruitPrices object with the key "str". However, with the first method, we make it clear that we want to access the member with the key stored inside the str variable, "oranges".
+ 5
In addition to the excellent answer posted by Jack McCarthy, the Javascript Map object is a great alternative to consider.
Check out the link below to better understand the differences between using objects vs Maps.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared
+ 1
Thanks