[英]JavaScript array[“index”].push() doesn't work
<script type="text/javascript">
var ar = [];
ar["index"].push("data1");
ar["index"].push("data2");
ar["index3"].push("data5");
ar[55].push("data7");
console.log(ar);
</script>
I get: TypeError: ar.index is undefined 我得到: TypeError:ar.index未定义
with this 有了这个
ar["index"].push("data1");
javascript tries to push "data1"
into an array. javascript尝试将
"data1"
推入数组。 The problem is that it expects an array, which ar["index"]
is not as it is undefined. 问题在于它期望一个数组,而
ar["index"]
不是未定义的数组。
You first need to initialize it 您首先需要初始化它
ar["index"] = [];
ar["index"].push("data1");
Try this :- 尝试这个 :-
<script type="text/javascript">
var ar = [];
ar["index"] = data1;
ar["index"] = data2;
.........
........
console.log(ar);
</script>
Array accepts the method push 数组接受方法push
What you wanna do is direct access, like a dictionary style... in this case, setting will just do the trick. 您想做的就是直接访问,就像字典样式一样。在这种情况下,设置就可以解决问题。
var ar = [];
ar["index"] = "data1";
If you're trying create an array of arrays you must check that the "inner" array exists. 如果尝试创建一个数组数组,则必须检查“内部”数组是否存在。 Something along the lines of this:
与此类似:
if(ar['index'] == null) {
ar['index'] = [];
ar['index'].push("data1");
} else {
ar['index'].push("data1");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.