简体   繁体   中英

Why does this associative array return undefined?

I don't know why this isn't working. I thought I've seen this in use a dozen times but it appears that I looked at it the wrong way judging from this:

var array = ["dog", "cat"];
console.log(array["dog"]); // undefined, why?
var array = {dog: "dog", cat: "cat"};
console.log(array["dog"]); // defined, why?

What you have is not an associative array, it does not act as such. A JavaScript object acts as such. The object's literals are {} , not [] .

Because you haven't set a value for the key "dog".

var array = {"dog":"woof", "cat":"meow"}
console.log(array["dog"]); // returns woof

That's not an associative array. As a matter of fact, associative arrays don't exist in JavaScript. If you want something which behaves similarly, use an object:

var animals = {dog: 123, cat: 456};
console.log(animals["dog"], animals.dog);

You've made an array with two elements:

array[0] = 'dog'
array[1] = 'cat'

This is not an associative array.

its not an associative array, just a regular array.

console.log(array[0]); // will give you dog

if you want associative array behavior create an object like so:

var dictionary = {"dog":"woof", "cat":"meow"};
console.log(dictionary["dog"]);

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