我想檢查是否有任何特定的鍵在JavaScript數組中有對象的值。檢查是否有任何特定的鍵在對象的JavaScript數組中有值
myArray = [ {file:null}, {file:hello.jpg}, {file:null}] ;
關鍵file
有值,以便返回true
否則false
。 如何以編程方式檢查此問題?
我想檢查是否有任何特定的鍵在JavaScript數組中有對象的值。檢查是否有任何特定的鍵在對象的JavaScript數組中有值
myArray = [ {file:null}, {file:hello.jpg}, {file:null}] ;
關鍵file
有值,以便返回true
否則false
。 如何以編程方式檢查此問題?
由於null
是falsy值,你可以用雙重否定來檢查它是否包含值或者是空的(null
)。
let myArray = [ {file:null}, {file:'hello.jpg'}, {file:null}];
const check = arr => arr.map(v => !!v.file);
console.log(check(myArray));
試試這個:
var myArray = [ {file: null}, {file: 'hello.jpg'}, {file: null}];
for(var i = 0; i < myArray.length; i++) {
if(myArray[i].file != null) {
console.log(myArray[i]);
}
}
你想看看地圖/過濾/減少,還有很多onlne解釋,像https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209
您情況下,您要映射:
items = myArray.map(item => !!item.file);
使用來測試數組的任何元素是否與條件匹配。
myArray = [{
file: null
}, {
file: "hello.jpg"
}, {
file: null
}];
var result = myArray.some(e => e.file);
console.log(result);
'obj.key === value''?另外 - 一個'for'循環。 – zerkms
沒有for循環。但可能會使用過濾器。 – kaws
如果我理解正確,可以使用'Array#some()'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some。問題仍然有點模糊 – charlietfl