我有一个产品的JSON对象。在对象中,我想检查是否有任何产品的featured
密钥设置为true
。如果键存在于对象中的任何位置,我想在结果上方添加一个h3
。
假设我有一个有4个产品的对象,其中一个产品的featured
键设置为true
,我该如何调整此代码,使h3只添加一次(目前它被添加了4次(?
var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});
在$.each
回调中添加return false
以打破循环
var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) {
searchResult += '<h3>Featured</h3>';
return false;
}
});
您可以使用Array#find()
或Array#some()
而不是来缩短此时间
var searchResult = '';
var featured = products.some(function(prod){ return prod.featured});
if(featured){
searchResult += '<h3>Featured</h3>';
}
只要有一个变量为您保留featured
状态,并在循环中修改它(如果有匹配的(
var searchResult = '';
var featured = false;
$.each(products, function (id, product) {
if (products[id].featured) { featured = true; }
});
if(featured === true){
searchResult += '<h3>Featured</h3>';
}