问题描述
我无法正常使用我的功能。根据条件,我希望函数通过推入新数组来返回新数组。如果if条件为假,我想返回两个不同的字符串消息。这是我的数据集的示例:
let items = [
{
itemName: "Effective Programming Habits",type: "book",price: 18.99
},{
itemName: "Creation 3005",type: "computer",price: 399.99
},{
itemName: "Orangebook Pro",price: 899.99
}
到目前为止,当我的函数接受一个项目数组和一个项目类型作为字符串搜索词时,它将返回一个项目数组,这些项目的类型与通过函数传递的类型匹配。但是,我也希望我的函数返回另外两件事。
如果购物车数组中没有商品,则返回字符串“您的购物车中没有任何商品”。这不是写成matches.length === 0
吗?
如果没有与给定类型匹配的项目,则返回字符串“找不到该类型的项目。请搜索其他项目。”。这不是写成if (search != items[i].type)
吗?
在给定条件的情况下,我如何使这两个字符串也返回?我感觉好像我被这些语句的执行顺序绊倒了。到目前为止,这是我的代码,没有两个字符串返回值。
function findItems (items,search) {
let matches = [];
for (i = 0; i < items.length; i++) {
if (items[i].type.includes(search)) {
matches.push(items[i])
}
}
return matches;
}
总而言之,如果搜索匹配,我希望函数返回一个数组。如果第一个条件为假,则我要根据新条件返回其他两个字符串消息之一。
解决方法
您可以在函数中添加一些条件,以根据所描述的条件返回适当的字符串:
let items = [{
itemName: "Effective Programming Habits",type: "book",price: 18.99
},{
itemName: "Creation 3005",type: "computer",price: 399.99
},{
itemName: "Orangebook Pro",price: 899.99
}
];
function findItems(items,search) {
if (items.length === 0) {
return "Your cart does not have any items in it.";
}
let matches = [];
for (i = 0; i < items.length; i++) {
if (items[i].type.includes(search)) {
matches.push(items[i])
}
}
if (matches.length === 0) {
return "No items found of that type. Please search for a different item."
}
return matches;
}
console.log(findItems(items,'computer'));
console.log(findItems(items,'software'));
console.log(findItems([],'computer'));
请注意,如果采用这种方法,则需要检查函数的返回值以查看它是数组还是字符串,并以不同的方式处理结果。
,您可以返回一个对象,而不是返回一个项目数组。然后,当您使用函数的返回值时,可以检查对象属性以获取消息或任何希望获取的消息。在以下函数中检查outputVal对象。
function findItems (items,search) {
let outputVal = { Message: "",matches: [] }
for (i = 0; i < items.length; i++) {
if (items[i].type.includes(search)) {
outputVal.matches.push(items[i])
}
}
if(outputVal.matches.length==0){
outputVal.Message = "No Items Found!"
}
return outputVal;
}
,
您也可以使用Array.filter
来实现。
let items = [{itemName:"Effective Programming Habits",type:"book",price:18.99},{itemName:"Creation 3005",type:"computer",price:399.99},{itemName:"Orangebook Pro",price:899.99}];
const filterItems = (items,searchText) => {
if(items.length === 0) {
return "Your cart does not have any items in it.";
}
const filteredItems = items.filter(item => item.type.includes(searchText));
return filteredItems.length === 0 ? "No items found of that type. Please search for a different item.": filteredItems;
}
//One matching type from the list
console.log(filterItems(items,"book"));
//No matching types from the list
console.log(filterItems(items,"not found"));
//When the cart items are empty
console.log(filterItems([],"book"));
//Multiple matching types form the list
console.log(filterItems(items,"computer"));
.as-console-wrapper {
max-height: 100% !important;
}