Why can I add named properties to an array as if it were an object?

前端 未结 7 2211
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:33

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray[\'A\'] = \"Athens\";
myArray[\'B\'] = \"Berlin\";
         


        
7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:12

    You can add named properties to almost anything in javascript but that doesn't mean that you should. Array in javascript should be used as a list, if you want an associative array use Object instead.

    Beware that if you really want to use an Array with named properties instead of Object those properties won't be accessible in a for...of loop and you might also get unexpected results when JSON encoding it to pass it around. See example below where all non-numeric indexes get ignored:

    let arr = [];
    let obj = {};
    
    arr['name'] = 'John';
    obj['name'] = 'John';
    
    console.log(arr);    // will output [name: "John"]
    console.log(obj);    // will output {name: "John"}
    
    JSON.stringify(arr); // will return [] <- not what you expected
    JSON.stringify(obj); // will return {"name":"John"}
    

提交回复
热议问题