所以为了解释这一点,我正在创建一个JSON对象,并且使用这个对象,我希望能够像PHP数组一样修改它。这意味着我可以在任何给定时间向键添加更多值到数组中。
例如,PHP是这样的:
$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
你可以看到 PHP 可以使用 'car' 键将更多数据添加到数组对象中。我想对 JSON 对象做同样的事情,除了它可能并不总是作为键的字符串。
function count(JSONObject) {
return JSONObject.length;
}
test = {};
test[100] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
我知道你可以像这样创建新对象,但这不是我想要做的。
test[101] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
这是我能想到的,但我知道它不起作用:
test[100][count(test[100])] { // Just a process to explain what my brain was thinking.
charge: "N",
mannum: "7",
canUse: "N"
}
我希望结果有点像这样(它也不必看起来像这样):
test[100][0] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
test[100][1] {
charge: "N",
mannum: "7",
canUse: "N"
}
我该如何做到这一点,以便我可以向对象中添加更多数据?我感谢大家的投入,帮助我找到解决方案甚至一些知识。
似乎这就是您想要的:
test = {};
test[100] = [{ // test[100] is an array with a single element (an object)
charge: "O",
mannum: "5",
canUse: "Y"
}];
// add another object
test[100].push({
charge: "N",
mannum: "7",
canUse: "N"
});
详细了解阵列。
如果我理解得很好,你正在尝试将其转换为 javascript:
.PHP
$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
JAVASCRIPT
var array = {};
array['car'] = ['blue', 'green', 'purple'];
解释
PHP 关联数组 -> {} in JSON
PHP 索引数组 -> [] 在 JSON 中
UPDATE1
我希望结果有点像这样(它也没有 必须看起来像这样):
test[100][0] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
test[100][1] {
charge: "N",
mannum: "7",
canUse: "N"
}
试试这个:
var test = {};
test[100] = [{"charge": "O", "mannum": "5", "canUse": "Y"}, {"charge": "N", "mannum": "7", "canUse": "N"}];