如何在for-in循环中使用If语句?

时间:2018-12-31 20:19:11

标签: javascript arrays object for-loop multidimensional-array

只想让自己对数组和in循环中的嵌套对象更加满意。一切都会按照我的预期进行,直到我插入一个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)
    }
  }
}

如果该值等于“ Shark”,我想将控制台日志设置为true

5 个答案:

答案 0 :(得分:3)

您还需要迭代数组

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);
            }
        }
    }
}

一种较短的方法是依次迭代animalslist

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);
    }
});

答案 1 :(得分:1)

要获得预期结果,请使用include

animals[i][prop].includes('Shark')

问题:代码中的动物[i] [prop]返回每个对象属性和值-Shark是数组元素之一

请在下面找到工作代码

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])
   console.log(animals[i][prop].includes('Shark'))

}
}

答案 2 :(得分:1)

您可以使用下面的代码

animals.flatMap(a=> a.list).filter(a=> a==='Shark').forEach(a=> console.log('true'))

答案 3 :(得分:0)

这是一种利用Array.prototype.forEach和ES6对象分解的方法:

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(function(el) {
  var {
    species,
    list
  } = el;

  list.forEach(function(s) {
    if (s === 'Shark') {
      console.log('Found shark');
    }
  })
});

答案 4 :(得分:0)

我想为可能的解决方案添加一种实用的方法:

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'] }];

const searchQuery = 'Shark';

function fishForSharks(animal) {
  return animal.list.includes(searchQuery);
}

function getKeyPositionFromValue(obj) {
  return Object.keys(obj.list).find(key => obj.list[key] === searchQuery);
}

function output(obj) {
  const output = document.querySelector('.output');

  output.innerHTML += `
  <li>
The <strong>${obj.species}</strong> species 
contains a ${searchQuery} at position: 
${getKeyPositionFromValue(obj)}
  </li>`;
}

animals.filter(fishForSharks).map(output);
<ul class="output"></ul>

http://jsfiddle.net/ujf1t2p0/