![](/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.