新手在這里。
我遇到了一個簡單的挑戰,目標很簡單,將轎車推入另一個陣列,因此呼叫該函式時的輸出(無法使用 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");
}
uj5u.com熱心網友回復:
我猜carsarg 是包含您要迭代的汽車的那個。
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。if 在 for willbreak;函式里面。
uj5u.com熱心網友回復:
由于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
uj5u.com熱心網友回復:
你的filterCars函式return在他們的函式中對我來說似乎不是很清楚,特別是因為你return在for回圈迭代中觸發你的。
這可能是您正在尋找的:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347352.html
標籤:javascript 数组 目的
