我有这段代码:
<?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);
});
});
现在item确实包含正确的值,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和item,但在此代码行meal_qty[meal_label_qty] = [];
之后开始编写Object
答案 0 :(得分: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);