econst ELEMENT_DATA: PeriodicElement[] = [
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}
];
如果值在此数组内部,如何返回布尔值?
像这样
ELEMENT_DATA.includes({name: 'Helium'});
>True
答案 0 :(得分:1)
使用Array.some方法将测试数组中至少一个元素是否通过测试
const ELEMENT_DATA = [{
position: 1,
name: 'Hydrogen',
weight: 1.0079,
symbol: 'H'
},
{
position: 2,
name: 'Helium',
weight: 4.0026,
symbol: 'He'
},
{
position: 3,
name: 'Lithium',
weight: 6.941,
symbol: 'Li'
},
{
position: 4,
name: 'Beryllium',
weight: 9.0122,
symbol: 'Be'
}
];
let m = ELEMENT_DATA.some(function(item) {
return item.name === 'Helium'
});
console.log(m)
答案 1 :(得分:1)
您可以移交用于检查对象的数组,键和值。
function check(array, key, value) {
return array.some(object => object[key] === value);
}
var periodicElements = [{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' }, { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }, { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' }, { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' }];
console.log(check(periodicElements, 'name', 'Helium'));