正在检查javascript数组中的数字索引

Checking for a numerical index in a javascript array

本文关键字:数字 索引 数组 检查 javascript      更新时间:2023-09-26

我正在接收通过数字索引聚合的json数据。

例如,当我在forloop中时,索引可能从1开始,这意味着在我的forloop中将发生错误,因为0不存在。

如何检查javascript数组中是否存在数字索引?

var a = [1, 2, 3], index = 2;
if ( a[index] !== void 0 ) { /* void 0 === undefined */
    /* See concern about ``undefined'' below.        */
    /* index doesn't point to an undefined item.     */
}

您应该能够使用for(key in data)

var data = [];
data[1] = 'a';
data[3] = 'b';
for(var index in data) {
  console.log(index+":"+data[index]);
}
//Output:
// 1-a
// 3-b

如果索引不连续,它将在数据中的每个关键项上循环。

如果您实际描述的是Object而不是Array,但与数组类似,因为它具有uint32_t的属性,但不存在基本的length属性。然后你可以把它转换成一个像这样的真实数组。浏览器兼容性方面,这需要支持hasOwnProperty

Javascript

function toArray(arrayLike) {
    var array = [],
        i;
    for (i in arrayLike) {
        if (Object.prototype.hasOwnProperty.call(arrayLike, i) && i >= 0 && i <= 4294967295 && parseInt(i) === +i) {
            array[i] = arrayLike[i];
        }
    }
    return array;
}
var object = {
    1: "a",
    30: "b",
    50: "c",
},
array = toArray(object);
console.log(array);

输出

[1: "a", 30: "b", 50: "c"]`

关于jsfiddle

好的,现在您有了一个稀疏的数组,并且想要使用for循环来做一些事情。

Javascript

var array = [],
    length,
    i;
array[1] = "a";
array[30] = "b";
array[50] = "c";
length = array.length;
for (i = 0; i < length; i += 1) {
    if (Object.prototype.hasOwnProperty.call(array, i)) {
        console.log(i, array[i]);
    }
}

Ouput

1 "a"
30 "b"
50 "c"

关于jsfiddle

或者,如果浏览器支持Array.prototype.forEach,也可以使用我链接的MDN页面上提供的可用填充程序,或es5_shim

Javascript

var array = [];
array[1] = "a";
array[30] = "b";
array[50] = "c";
array.forEach(function (element, index) {
    console.log(index, element);
});

输出

1 "a"
30 "b"
50 "c"

在jsfiddle 上