• 请不要在回答技术问题时复制粘贴 AI 生成的内容
yantianqi
V2EX  ›  程序员

javascript 数组用[]不可以声明关联数组,但是可以存放关联数组?

  •  1
     
  •   yantianqi · Oct 18, 2016 · 2817 views
    This topic created in 3518 days ago, the information mentioned may be changed or developed.
    var a = ["name","age","sex"];
    var b = ["lisi",18,"man"];
    var arr = new Array();
    for(var i = 0; i < a.length; i++) {
    arr[a[i]] = b[i];
    }
    console.log(arr);
    3 replies    2016-10-18 22:58:50 +08:00
    prefere
        1
    prefere  
       Oct 18, 2016
    Array 是个对象吧, alert(arr)
    wssgcg1213
        2
    wssgcg1213  
       Oct 18, 2016
    数组的本质是对象,它的原型链:[] -> Array.prototype -> Object.prototype
    ianva
        3
    ianva  
       Oct 18, 2016
    对象也能作为数组用,所以对象可以当关联数组也可以当数组用
    比如:
    var a = {};
    Array.prototype.push.call( a,11);
    console.log( a.length ) // 你会发现会有了 length 属性并为 1
    a 就成了一个类数组
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   919 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 19:36 · PVG 03:36 · LAX 12:36 · JFK 15:36
    ♥ Do have faith in what you're doing.