drj26159 2015-11-03 08:49
浏览 23
已采纳

向对象添加条目

A php script is computing me the following array:

$test = Array();
$test['a'] = Array();
$test['a']['a1'] = 'a1';
$test['a']['a2'] = 'a2';
$test['b'] = Array();
$test['b']['b1'] = 'b1';
$test['b']['b2'] = 'b2';

I'm converting this array into JSON using:

echo json_encode($test);

I'm retrieving this JSON using an Ajax call, and I'm turning this it into a JavaScript array using:

test = JSON.parse(data);

My question is: How can I add entries to this array in JavaScript? I tried:

test['c'] = [];
test['c']['c1'] = 'c1';
test['c']['c2'] = 'c2';

But then in the console test['c'] is empty (Array[0]).

  • 写回答

2条回答 默认 最新

  • duanhao7786 2015-11-03 08:57
    关注

    After this point:

    test = JSON.parse(data);
    

    you're not dealing with JSON anymore; test is an object.

    ...and I'm turning this it into a JavaScript array using...

    You're not turning it into a JavaScript array, you're turning it into a JavaScript object. JavaScript's nearest equivalent to PHP's "associative array" is an object, not an array.

    To add properties to objects, you just assign to them. In your case, you're trying to create a property named c that's an object with additional properties. Since we use objects, not arrays, for that in JavaScript, you'd create c using {} rather than []. E.g.:

    test['c'] = {};
    test['c']['c1'] = 'c1';
    test['c']['c2'] = 'c2';
    

    or more concisely:

    test.c = {};
    test.c.c1 = 'c1';
    test.c.c2 = 'c2';
    

    or even more concisely:

    test.c = {
        c1: 'c1',
        c2: 'c2'
    };
    

    What you were doing would work, because normal JavaScript arrays are really objects and so you can add arbitrary, non-element properties to them as well as using them in the more "normal" way. But in the normal case, you'd use non-array objects instead.

    But then in the console test['c'] is empty (Array[0])

    That's because the console is showing you the array-like aspects of the object and ignoring the non-array aspects. But test['c'] did have c1 and c2 properties, the console just didn't show them to you. Nevertheless, only use non-index property names with arrays if you have a specific reason for doing so. Otherwise, again, use non-array objects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了