javascript - 如何在 for-in 循环中使用 If 语句?
问题描述
只是试图让数组中的嵌套对象和循环中的嵌套对象更加舒适。一切都按我的预期工作,直到我插入一个 if 语句,然后我没有得到我在控制台中输出 true 的预期结果。
我已经尝试过各种点/括号符号的组合来访问。
const animals = [
{
species: 'Pets',
list: [
'Dog',
'Cat',
'Rabbit',
'Gerbil',
'Turtle',
'Canary'
]
},
{
species: 'Wild',
list: [
'Bear',
'Lion',
'Deer',
'Tiger',
'Cougar',
'Elk',
'Beaver',
'Elephant',
'Rhino'
]
},
{
species: 'Marine',
list: [
'Shark',
'Salmon',
'Squid',
'Octopus',
'Jellyfish'
]
}
];
for(let i = 0; i < animals.length; i++) {
for(let prop in animals[i]) {
console.log(animals[i][prop])
if(animals[i][prop] === 'Shark'){
console.log(true)
}
}
}
如果值等于“鲨鱼”,我想控制台日志为真
解决方案
您还需要迭代数组
const animals = [{ species: 'Pets', list: ['Dog', 'Cat', 'Rabbit', 'Gerbil', 'Turtle', 'Canary'] }, { species: 'Wild', list: ['Bear', 'Lion', 'Deer', 'Tiger', 'Cougar', 'Elk', 'Beaver', 'Elephant', 'Rhino' ] }, { species: 'Marine', list: ['Shark', 'Salmon', 'Squid', 'Octopus', 'Jellyfish'] }]
for (let i = 0; i < animals.length; i++) {
for (let prop in animals[i]) {
// console.log(animals[i][prop]);
for (var item of animals[i][prop]) {
if (item === 'Shark') {
console.log(true);
}
}
}
}
更短的方法是迭代animals
然后list
.
const animals = [{ species: 'Pets', list: ['Dog', 'Cat', 'Rabbit', 'Gerbil', 'Turtle', 'Canary'] }, { species: 'Wild', list: ['Bear', 'Lion', 'Deer', 'Tiger', 'Cougar', 'Elk', 'Beaver', 'Elephant', 'Rhino' ] }, { species: 'Marine', list: ['Shark', 'Salmon', 'Squid', 'Octopus', 'Jellyfish'] }]
animals.forEach(({ list }) => {
if (list.includes('Shark')) {
console.log(true);
}
});