任何人都可以解释为什么第二个警报说0?
var pollData = new Array();
pollData['pollType'] = 2;
alert(pollData['pollType']); // This prints 2
alert(pollData.length); // This prints 0 ??
Run Code Online (Sandbox Code Playgroud)
只有在添加数字索引时才会更改数组的长度.例如,
pollData["randomString"] = 23;
Run Code Online (Sandbox Code Playgroud)
对长度没有影响,但是
var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46
Run Code Online (Sandbox Code Playgroud)
将长度更改为46.请注意,如果键是数字或字符串,则无关紧要,只要它是数字整数即可.
此外,您不应该以这种方式使用数组.考虑更多的副作用,因为数组也是对象,而在JavaScript中,任何对象都可以将任意键作为字符串.
| 归档时间: |
|
| 查看次数: |
4726 次 |
| 最近记录: |