Checking for a numerical index in a javascript array [closed]

杀马特。学长 韩版系。学妹 提交于 2019-12-18 14:03:50

问题


I'm receiving json data that is aggregated by numerical indexes.

When I'm in my forloop, for example, the index might start at 1, which means in my forloop an error would occur because 0 doesnt exist.

How do I check if a numerical index exists in the javascript array?


回答1:


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.     */
}



回答2:


You should be able to use 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

Which will loop over each key item in data if the indexes aren't contiguous.




回答3:


If what you are actually describing is an Object rather than an Array, but is array like in the fact that it has properties that are of uint32_t but does not have essential length property present. Then you could convert it to a real array like this. Browser compatibility wise this requires support of 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);

Output

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

On jsfiddle

Ok, now you have a sparsely populated array and want to use a for loop to do something.

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"

On jsfiddle

Alternatively, you can use Array.prototype.forEach if your browser supports it, or the available shim as given on the MDN page that I linked, or es5_shim

Javascript

var array = [];

array[1] = "a";
array[30] = "b";
array[50] = "c";

array.forEach(function (element, index) {
    console.log(index, element);
});

Output

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

On jsfiddle



来源:https://stackoverflow.com/questions/17245397/checking-for-a-numerical-index-in-a-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!