我有一个看起来像这样的数组:
var array = [[10, 8, 2], [5, 7, 1], [3, 9, 4]];
我需要一些东西告诉我子对象是否存在,而不会抛出错误。这是一个例子:
elementExsits(array[0][4]);
//false
elementExsists(array[1][2]);
//true
函数elementExsists
将验证路径是否存在。我试过了:
if (typeof array[3][2] !== 'undefined') {};
但它只是说
Cannot read property '2' of undefined
您一次检查一个房产。如果遇到undefined,请停止:
if (typeof array[3] !== "undefined" && typeof array[3][2] !== "undefined") {
}
或更好:
if (3 in array && 2 in array[3]) {
}
一个简单的if语句可以决定一个元素是否存在:
var array = [[10, 8, 2], [5, 7, 1], [3, 9, 4]];
if (array[1] && array[1][2]) {
console.log('exists');
} else {
console.log('doesn\'t exist');
}
if (array[10] && array[10][2]) {
console.log('exists');
} else {
console.log('doesn\'t exist');
}
尝试访问不存在的数组值会返回undefined
,因此if语句将根据结果进行切换。
Salman's answer适用于您的场景。或者,您还可以创建一个动态函数来返回索引处的值,如果未找到则返回undefined。
var array = [[10, 8, 2], [5, 7, 1], [3, 9, 4]];
function elementExists(array, ...indices){
return indices.reduce((el, i) => el && el[i], array)
}
console.log(elementExists(array, 0, 4))
console.log(elementExists(array, 1, 2))
console.log(elementExists(array, 3, 2))
您可以获取数组和索引列表,并使用Array.every()
迭代索引。如果所有索引都不是undefined
,则元素存在。如果事件一是undefined
,则该元素不存在。
const elementExists = (array, ...indexes) => {
let current = array;
return indexes.every(index => {
current = array[index];
return current !== undefined;
});
};
const array = [[10, 8, 2], [5, 7, 1], [3, 9, 4]];
console.log(elementExists(array, 0, 4)); // false
console.log(elementExists(array, 1, 2)); // true
console.log(elementExists(array, 3, 2)); // false
function elementExists(a, i, j) {
return Array.isArray(a) && Array.isArray(a[i]) && a[i].length > j;
}
console.log(elementExists(null, 0, 1));
console.log(elementExists(undefined, 0, 1));
console.log(elementExists(0, 0, 1));
console.log(elementExists('foo', 0, 1));
console.log(elementExists([], 0, 1));
console.log(elementExists([null], 0, 1));
console.log(elementExists([0], 0, 1));
console.log(elementExists([[]], 0, 1));
console.log(elementExists([[],[]], 0, 1));
console.log(elementExists([[3],[9]], 0, 1));
console.log(elementExists([[3,2],[9]], 0, 1));
您可以使用in
operator并检查索引是否存在。然后继续下一个嵌套数组。
如果索引不在给定数组中,此解决方案适用于数组和索引数组,并使用与Array#every
的短路。
function elementExsists(array, indices) {
return indices.every(i => Array.isArray(array) && i in array && (array = array[i], true))
}
var array = [[10, 8, 2], [5, 7, 1], [3, 9, 4]];
console.log(elementExsists(array, [0, 4])); // false
console.log(elementExsists(array, [1, 2])); // true