2017-05-18 42 views
1

我有这样的代码:关联数组不正常

<?php 
if(mysqli_num_rows($result2) >= 2){ 
foreach($label_name as $meal_option_id => $names_of_labels) 
{ 
    echo '<button price='.$protein_prices[$meal_option_id].' label_option= '.$meal_option_id.' data-label-option= '.$meal_option_id.' class="view1 white cbtn1 open_sansbold option protein-option">' .$names_of_labels. ' <span id="price-difference-for-'.$meal_option_id.'"></span></button>'; 
}}?> 

的Javascript:

$(function() { 
    var meal_qty = new Array(); 
    var label_options = new Array(); 
    var qty_options = new Array(); 

    $(".protein-option").click(function() { 
     var meal_label_qty = $(this).data("label-option"); 
     // CREATE THE ASSOCIATIVE LABEL 
     meal_qty[meal_label_qty] = []; 
     // CREATE THE OBJECT WITH VALUES 
     var item = { 
      mon: $("#qty1").val(), 
      tues: $("#qty2").val(), 
      wed: $("#qty3").val(), 
      thur: $("#qty4").val(), 
      fri: $("#qty5").val() 
     } 
     // ADD TO ARRAY 
     meal_qty[meal_label_qty] = item; 

     console.log(meal_qty); 
    }); 
}); 

现在项目不包含正确的价值观也是如此meal_label_qty但我的控制台日志:

(1003) [undefined × 1002, Object] 

我想要这个输出:

[meal_label_qty] 
{ 
       mon: $("#qty1").val(), 
       tues: $("#qty2").val(), 
       wed: $("#qty3").val(), 
       thur: $("#qty4").val(), 
       fri: $("#qty5").val() //WHICH IS ITEM 
} 

我意识到自己的代码放在正确的meal_label_qty和项目,但启动该行代码meal_qty[meal_label_qty] = [];

回答

1

JavaScript没有关联数组后写对象;它有零索引数组和具有属性的对象。它可能是似乎就像有关联数组,因为您可以使用类似的语法(obj[property])从对象访问属性。

为了获得您想要的输出,只需将meal_qty更改为对象而不是数组,或者重新构造您的代码并将新对象推入数组,而不是将其分配给索引。

// add the quantity label to the item object 
item.qty = meal_label_qty; 

// push the whole object onto the array 
meal_qty.push(item); 
+0

我这样做 '变种meal_label_qty = $(本)。数据( “标签选项”); \t \t // \t创建具有值的对象 \t \t变种项= { \t \t \t周一:$( “#qty1”)VAL(), \t \t \t周二:$( “#qty2”) .VAL(), \t \t \t结婚:$( “#qty3”)VAL(), \t \t \t星期四:$( “#qty4”)VAL(), \t \t \t周五:$(” #qty5“)。val() \t \t} \t \t item.qty = meal_label_qty; \t \t meal_qty.push(item); \t \t alert(meal_qty); '我得到[object] [Object] – sarah

+0

索引数组总是一个数字“meal_label_qty”总是一个数字,所以它应该工作 – sarah

+0

'alert'只是对meal_qty对象做一个toString,这就是为什么你看到'[object object]'。我有点不清楚你在登录 – chazsolo