我已經學習 Javascript 幾個星期了(主要是陣列、函式、for 回圈和 if 陳述句)。我遇到了一個困擾我的問題,并且非常感謝任何形式的洞察力或問題的分解。
這是問題所在:
Create a function findItems that
? takes in two arguments: an array of items, and a type of item as a string
? returns an array of items that have a type that matches the type passed in
使用下面的示例資料, findItems(items, "book") /* =>
[{
itemName: "Effective Programming Habits",
type: "book",
price: 18.99
}]
*/
注意:在您撰寫此函式并且第一組測驗通過后,第二組測驗將顯示在第 2 部分。第 2 部分 - 查找專案,擴展
Add the following features to your findItems function:
? If there are no items in the cart array, return the string "Your cart does not have any items in it."
? If there are no items that match the given type, return the string "No items found of that type. Please search for a different item.".
Sample Shopping Cart Data
let items = [
{
itemName: "Effective Programming Habits",
type: "book",
price: 18.99
},
{
itemName: "Creation 3005",
type: "computer",
price: 399.99
},
{
itemName: "Orangebook Pro",
type: "computer",
price: 899.99
}
];
有人知道如何解決這個問題嗎?或者能夠提供它的細分?
uj5u.com熱心網友回復:
您應該遍歷給定的陣列,然后將帶有該type欄位的任何物件添加到臨時陣列中,然后回傳該陣列。像這樣的東西:
function findItems(arr, type) {
let temp = [];
for (let i = 0; i < arr.length; i ) {
const item = arr[i];
if (item.type === type) {
temp.push(item);
}
}
return temp;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481261.html
標籤:javascript 数组 功能 for循环
上一篇:PHP,更改多維陣列中的值
下一篇:蟒蛇|IF AND陳述句
