簡體   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