【发布时间】:2016-06-13 07:27:15
【问题描述】:
我正在编写一个程序,它获取商店库存并搜索该库存中的特定商品,将这些商品推送到数组中。清单都是一个对象,该对象中的每个对象都是清单中的一项。项目本身没有键——它们只是对象文字。因此,我坚持使用快速枚举(对于产品中的项目)循环遍历它们。每个项目如下所示:
{ id: 2759167427,
title: 'Practical Silk Bag',
handle: 'practical-silk-bag',
vendor: 'Legros, Willms and Von',
product_type: 'Bag'
}
当且仅当该项目是键盘或计算机时,我正在尝试将项目对象推送到数组。为此,我尝试使用这样的东西:
var kbComps = [];
//loop through the inventory, looking for everything that is a keyboard or a computer
for (var key in products) {
var item = products[key];
for (var property in item) {
if (item[property].includes("Computer") || item[property].includes("Keyboard")) {
kbComps.push(item);
}
}
}
但是我收到一个错误,告诉我包含不是定义的方法,这意味着程序没有将 item[title] 识别为字符串,所以现在我被卡住了。我将如何规避这一点?任何帮助表示赞赏。
祝大家好运
【问题讨论】:
-
我可能在那里遗漏了一些东西,但这些项目不只是字符串(不是对象)吗?
-
否定,该项目是我第一个代码片段中用大括号括起来的所有内容。所以它具有“id”、“title”、“handle”等属性。
-
现在我明白了,我的错
-
我猜您正在寻找“product_type”属性等于计算机或键盘的产品,对吧?
-
没错。我已经尝试删除“包含并且只使用纯粹的“if(item[property] == "Computer" | | item[property] == "Keyboard")"...但是,当我的代码运行和编译时,当我用 console.log 测试时它什么也不打印
标签: javascript string loops object