javascript - Why can't variables be used for js array key names? What should I do if I want to use variables as associative array keys like PHP?
给我你的怀抱
给我你的怀抱 2017-07-05 11:07:29
0
8
1103

When using the key name, an error is reported saying that the set property cannot be set

给我你的怀抱
给我你的怀抱

reply all(8)
習慣沉默

JS Object

var o = {
    name: 'foo', 
    hey: 'bar'
}
console.log(o.name); 
// => "foo"
console.log(o['name']); 
// => "foo"

Map object

The above-mentioned ordinary js objects can only use strings as keys. es6 has a new feature that allows "value" to be used as the key. See example:

var m = new Map(); 

var eczn = {
    name: 'eczn',
    age: 20
}

m.set(eczn, 'map Obj to Stirng'); 

console.log(m); 

黄舟

Arrays in JavaScript do not support using identifiers other than numbers as array subscripts, but you can use objects to achieve similar effects to associative arrays in PHP:

var myArray = {'key1': 'value1'};
console.log(myArray['key1']); // 会输出value1, 其实相当于myArray.key1
漂亮男人

JS arrays use custom key names, which I have never used in development for so long. There is no need for it at all. Just use Object.

曾经蜡笔没有小新

Yes, for example

var person = {
    "name" : "孤月"
};

var n = "name";

console.log(person[n]);
//设置键名
person[n] = "deep dark fantasy";
学霸

Original arrays cannot use characters other than numbers as key names. You can use objects as arrays to achieve the same functionality.

为情所困

When defined, arrays can only be indexed by numbers, for example, while other types of index are objects. This is different from php.

曾经蜡笔没有小新

JS does not have associative arrays, only basic arrays. What looks like associative arrays are objects. This js has them.

phpcn_u1582

JS arrays can be subscripted with strings. Similar to associative arrays, the type of array subscript in JS is strings

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!