Firebug在数组中显示大量未定义的条目

Firebug is displaying lots of undefined entries in a array

本文关键字:未定义 数组 显示 Firebug      更新时间:2023-09-26

我正在定制<select>,但是我遇到了一个问题。快速的console.log(options);显示了数组的结果:

[未定义,未定义,"Selena Gomez","Mila Kunis",未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,"Miley Cyrus"]

也当我做alert(options.length);的结果是12。而实际上,在select.

中有4个选项。

生成数组的代码:

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); 
});

这里有一些误导性的回答:

  1. Javascript数组索引是字符串。数组只是具有特殊长度属性和一些方便方法的对象,但除此之外,它们只是对象。它们的属性是字符串。数值属性将被视为索引,并用于设置长度属性。

  2. 没有"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;
  }
}