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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么