![](/img/trans.png)
[英]Testing for existence of enumeration value in a JavaScript associative array
[英]Testing Existence of a Sparse Array Element in JavaScript?
在多层结构中测试数组元素是否存在的最佳方法是什么? 例如:
if (typeof arr[a][b][c] === 'undefined') { ...do something... }
如果[a]或[b]不存在,我们将无法测试[c]。
是否有下划线或lodash函数来处理此问题?
你可以做
if (arr && arr[a] && arr[a][b] && typeof arr[a][b][c] === 'undefined') { ...do something... }
或者您可以创建一个自定义函数
function check(arr){ let temp = arr; for(let i=1; i<arguments.length; i++){ if(temp[arguments[i]] == undefined){ return false; } temp = temp[arguments[i]]; } return true; } let arr= [[[1], [2]], [3]]; console.log(check(arr, 0, 0)); console.log(check(arr, 0, 0, 0, 0));
您可以在很多地方创建函数:
function get(obj, props) {
return props.reduce(function(x, p) { return x && x[p] ? x[p] : null }, obj)
}
if (get(arr, [a, b, c])) ...
适用于对象和数组:
var obj = [0, {a: [0, 'value', 2]}, 2]
get(obj, [1, 'a', 1]) //=> 'value'
get(obj, [1, 'a', 8]) //=> null
对于稀疏数组检查,仅检查undefined
的项是不够的。 但是,您可以使用in
运算符进行测试,例如
(a,b,c) in arr
var a = []; a[10] = 1; b = 10; console.log(1 in a) console.log((1,2,3) in a) console.log(b in a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.