繁体   English   中英

使用循环遍历数组将嵌套在内部的键值推送到另一个数组中。 Javascript

[英]Using loop-for through array to push key-values nested inside, into a different array. Javascript

新手在这里。

我遇到了一个简单的挑战,目标很简单,将轿车推入另一个数组,因此调用function时的output(不能使用console.log,将被忽略)是:

[ { type:'sedan', size: 'white'}, { type:'sedan', color:'red'} ].

建议是使用 push()。

这是我糟糕的代码。

欢迎任何帮助!

function filterCars (cars) {
     const sedanCars = []
     const carArr = [
      { type: 'sedan', color: 'white'},
      { type: 'truck', color: 'blue'},
      { type: 'sedan', color: 'red'},
      { type: 'coupe', color: 'red'}
      ]
   
    var arrayLength = carArr.length;
    for (var i = 0; i < arrayLength; i++) {
    console.log(carArr[i]);
        
  if(carArr.type==="sedan") {
          return sedanCars.push("sedan");
        }

我猜cars arg 是包含您想要迭代的汽车的那个。

function filterCars(cars) {
    const sedanCars = []
    const arrayLength = cars.length;
    for (let i = 0; i < arrayLength; i++) {
        if (cars[i].type === "sedan") sedanCars.push(cars[i]);
    }
    return sedanCars
}

return语句应该在function的末尾。 如果在 for 里面,就会break; 功能。

由于push只是一个建议,我会推荐一种使用数组filter方法的更现代的方法:

const cars = [
  { type: 'sedan', color: 'white'},
  { type: 'truck', color: 'blue'},
  { type: 'sedan', color: 'red'},
  { type: 'coupe', color: 'red'},
];

const sedans = cars.filter(car => car.type === 'sedan');

filter方法采用一个回调函数,该函数在数组的每个元素上调用。 如果它返回一个真值,那么该项目将包含在结果数组中。

在 MDN 上阅读有关过滤器的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

你的filterCars函数和return在它们的函数中对我来说似乎不太清楚,特别是因为你在for循环迭代中触发你的return

这可能是您正在寻找的:

 function getSedans(cars) { return cars.filter(car => car.type === 'sedan') } const carArr = [ { type: 'sedan', color: 'white' }, { type: 'truck', color: 'blue' }, { type: 'sedan', color: 'red' }, { type: 'coupe', color: 'red' } ]; const sedanCars = [...getSedans(carArr)]; // including this console.log to provide the output console.log(sedanCars);

如果你真的更喜欢使用push()这里是另一种方法:

 const sedanCars = []; const carArr = [ { type: 'sedan', color: 'white' }, { type: 'truck', color: 'blue' }, { type: 'sedan', color: 'red' }, { type: 'coupe', color: 'red' } ]; for (const car of carArr) { if (car.type = 'sedan') sedanCars.push(car); } // including this console.log to provide the output console.log(sedanCars);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM