Firebug在数组中显示大量未定义的条目
Firebug is displaying lots of undefined entries in a array
我正在定制<select>
,但是我遇到了一个问题。快速的console.log(options);
显示了数组的结果:
[未定义,未定义,"Selena Gomez","Mila Kunis",未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,"Miley Cyrus"]
也当我做alert(options.length);
的结果是12。而实际上,在select.
生成数组的代码:
var options = new Array;
$(this).children('option').each(function () {
if ($(this).val()) {
options[$(this).val()] = $(this).text();
}
});
console.log(options);
我不知道是什么问题…我添加了if ($(this).val())
,以确保没有静态元素进入数组,但仍然
注意:然而,当我在firebug中打开数组时,它只显示正确的条目
$(this).val()
不能是0,1,2,3,而是2,3,11(第四个在哪里?)
使用options.push($(this).text());
代替,或者使用它作为对象,以避免自动生成缺失的索引。
此外,$(this).val()
将评估为false
,如果它是空""
或0
,是第4个可能吗?
我猜$(this).val()
代表$(this).text()
的"Selena Gomez"是2号,"Miley Cyrus"是11号。试试这个:
options.push($(this).text()); // ensure that your array is filled as an array
例如,这在javascript
中是可以的var a = [];
a[4] = 'test';
a["something"] = this;
和console.log将显示
[undefined, undefined, undefined, undefined, 'test']
试试这个
var options = [];
$(this).children('option').each(function () {
if ($(this).val()) {
options.push($(this).text());
}
});
console.log(options.join(","));
如果需要文本键,则使用javascript对象作为关联数组。
var options = {};
$(this).children('option').each(function () {
if ($(this).val()) {
options[$(this).val()] = $(this).text();
}
});
$.each(options, function(key, value) {
console.log(key + ': ' + value);
});
这里有一些误导性的回答:
-
Javascript数组索引是字符串。数组只是具有特殊长度属性和一些方便方法的对象,但除此之外,它们只是对象。它们的属性是字符串。数值属性将被视为索引,并用于设置长度属性。
-
没有"missing keys"。如果创建一个稀疏数组,它的长度将被设置为最高索引+ 1。如果从0到长度-1遍历所有索引,则任何不存在的索引都将返回undefined
。
var a = [];
a[0] = 'zero';
a[4] = 'four';
console.log(a.length); // 5
console.log(a); // ["zero", undefined, undefined, undefined, "four"]
console.log(a[1]); // undefined
console.log(a.hasOwnProperty(1)); // false
仅仅因为Firebug将索引1到3包含在undefined中,并不意味着它们存在。
OP的简单循环版本是:
var opts = this.options;
for (var i=0, iLen=opts.length; i<iLen; i++) {
if (opts[i].value) {
options[opts[i].value] = opts[i].text;
}
}
- JSON解析未从数组中获取值
- Join架构验证:Join.object定义数组中的有效键
- 值未与数组对象绑定
- 在定义数组后填充数组
- 带有自定义数组的迷你图
- 函数中的Javascript未定义数组
- Meteor会话变量未存储数组
- 如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组
- Javascript-自定义数组不起作用
- 为什么不能映射“未定义”数组
- JSON 多维数组未显示(“数组未定义”)
- 确定猫鼬中空数组和未定义数组之间的区别
- 未定义数组值
- 未捕获的类型错误:无法读取属性'长度'的未定义(数组)
- forEach()创建未定义数组(Javascript)
- Javascript console.log未读取数组未定义
- Jquery回调未定义数组
- Javascript拆分未定义数组
- 对array构造函数创建的未定义数组执行forEach操作
- 禁止未定义数组属性的javascript错误