我编写了一个迭代数组的函数,如果找到匹配则返回对象及其值。
不知何故,当我用它的参数调用函数时,它总是在浏览器控制台上打印undefined。
不确定我缺少什么,但在功能上,当我在console.log(v)时,我得到了值,但在调用函数时没有。
HTML code:
<div class="accounts">
1<input name="1" value="" /><br>
2<input name="2" value="" /><br>
3<input name="3" value="" /><br>
4<input name="4" value="" /><br>
5<input name="5" value="" /><br>
6<input name="6" value="" /><br>
7<input name="7" value="" /><br>
8<input name="8" value="" /><br>
9<input name="9" value="" /><br>
10<input name="10" value="" /><br>
11<input name="11" value="" /><br>
</div>
JQuery代码:
var vendor = [];
vendor = [{"vendor_id":"1","vendorname":"Coke","account_no":"34534554"},{"vendor_id":"2","vendorname":"Pepsi","account_no":"34634532"},{"vendor_id":"3","vendorname":"Dr. Pepper \/ 7 Up","account_no":"56754568"},{"vendor_id":"4","vendorname":"Frito Lay","account_no":"676554544"},{"vendor_id":"5","vendorname":"Blue Bunny","account_no":"678476543"},{"vendor_id":"6","vendorname":"Yummy","account_no":"9987654"},{"vendor_id":"7","vendorname":"Ork Farm","account_no":"23456767"},{"vendor_id":"8","vendorname":"Borden","account_no":"89765432"},{"vendor_id":"9","vendorname":"Highland","account_no":"2345678987"},{"vendor_id":"10","vendorname":"Nesquek","account_no":"798654324"}];
var getVendors = [];
$('.accounts input').each(function(){
getVendors.push($(this).attr('name'));
});
function vendorAcctCheck (array, value) {
array.filter(function(v) {
if (v.vendor_id == value) {
// console.log(v);
return v;
};
})
// return false;
}
var vendorData = vendorAcctCheck(vendor, "2");
console.log(vendorData)
这是我的JSFiddler link。
答案 0 :(得分:2)
你忘了回来。
您仅在过滤器的回调中使用return,但这仅适用于.filter
本身。
如果您想获取过滤数据,则返回过滤后的数据
试试这个
function vendorAcctCheck (array, value) {
return array.filter(function(v) {
if (v.vendor_id == value) {
// console.log(v);
return v;
};
})
// return false;
}