search

Home  >  Q&A  >  body text

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?

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

给我你的怀抱给我你的怀抱2709 days ago1125

reply all(8)I'll reply

  • 習慣沉默

    習慣沉默2017-07-05 11:09:29

    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); 

    reply
    0
  • 黄舟

    黄舟2017-07-05 11:09:29

    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

    reply
    0
  • 漂亮男人

    漂亮男人2017-07-05 11:09:29

    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.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:09:29

    Yes, for example

    var person = {
        "name" : "孤月"
    };
    
    var n = "name";
    
    console.log(person[n]);
    //设置键名
    person[n] = "deep dark fantasy";

    reply
    0
  • 欧阳克

    欧阳克2017-07-05 11:09:29

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

    reply
    0
  • 为情所困

    为情所困2017-07-05 11:09:29

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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:09:29

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

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 11:09:29

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

    reply
    0
  • Cancelreply