gpt4 book ai didi

javascript - 使用each()在对象数组中循环

转载 作者:行者123 更新时间:2023-12-01 07:37:08 25 4
gpt4 key购买 nike

我正在编写下面的代码。我正在尝试过滤并获取包含类似输入字符串的项目项的索引和值,但它不起作用。

var items =[  {item:"Saab", sku:"SA"},
{item:"Volvo", sku:"VO"},
{item:"BMW", sku:"BM"},
{item:"Toyota", sku:"TO"},
{item:"Honda", sku:"HO"},
{item:"Nissan", sku:"NI"},
];

$("#filter").keyup(function () {
var filter = $(this).val();

$(items['item']).each(function (index, value) {
if (value.search(new RegExp(filter, "i")) < 0) {
// Do somethign
} else {
console.log(index);
console.log(value);
}
});

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="live-search" action="" class="styled" method="post">
<fieldset>
<input type="text" class="text-input" id="filter" value="" />
<span id="filter-count"></span>
</fieldset>
</form>

最佳答案

您可能必须将项目作为常规 javascript 变量而不是 jquery 选择器获取。

var items = [
{ item: "Saab", sku: "SA" },
{ item: "Volvo", sku: "VO" },
{ item: "BMW", sku: "BM" },
{ item: "Toyota", sku: "TO" },
{ item: "Honda", sku: "HO" },
{ item: "Nissan", sku: "NI" },
];

$("#filter").keyup(function() {
var filter = $(this).val();

items.forEach(function(item, index) {
var value = item.item // Honda, Nissan
var sku = item.sku // HO, NI
if (filter !== '' && new RegExp(filter, "i").test(value)) {
// Do somethign when matched
console.info(index, value, sku)
} else {
// console.log(index);
// console.log(value);
}
});

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="live-search" action="" class="styled" method="post">
<fieldset>
<input type="text" class="text-input" id="filter" value="" />
<span id="filter-count"></span>
</fieldset>
</form>

关于javascript - 使用each()在对象数组中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61829573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com