如何解决jQuery grep有两个数组?
| 是我的语法,还是我试图做的完全错误的方法? 我有两个由用户选择的属性填充的数组。然后,我尝试在json文件上使用$ .grep()来选择与其搜索匹配的枕头。因此,在下面的示例中,我试图找到所有填充量为“羽绒”和价格为“低”的枕头。var activevars = [\'fill\',\'price\'];
var activeattributes = [\'down\',\'low\'];
pillowSelection = $.grep(data.pillow,function (a) {
return $.inArray(a[activevars],activeattributes) > -1;
});
我是一位顽强的Googler,但这让我感到困惑。非常感谢您提供任何线索。
解决方法
如果我理解正确,,1ѭ和
activeattributes
是并行数组,即that3ѭ和activeattributes[0]
一起使用,activevars[1]
和activeattributes[1]
一起去等等。
因此,您可以执行以下操作:
pillowSelection = $.grep(data.pillow,function(a) {
for (var i = 0; i < activevars.length; i++) {
if (a[activevars[i]] !== activeattributes[i]) {
return false;
}
}
return true;
});
如果您想要一种更具功能性的样式,则应使用一个表示活动属性/变量的对象(或仅从并行数组进行转换);例如。
var filter = { fill: \'down\',price: \'low\' };
然后检查它是否是每个枕头的子词典:
pillowSelection = $.grep(data.pillow,function(a) {
return sub_dictionary(filter,a);
});
,您的问题似乎缺少一些内容,但我将尝试这样回答:
如果您有一系列枕头对象:
var pillows = [
{ fill: \'down\',price: \'low\' },{ fill: \'cheese\',price: \'middle\' },{ fill: \'water\',price: \'high\' },{ fill: \'air\',price: \'omg-too-much\' }
];
要获得符合您条件的新枕头系列,请以这种方式构成查询,这将更加容易:
var query = { fill: \'down\',price: \'low\' };
var matches = pillows.filter(function (pillow) {
return pillow.fill === query.fill && pillow.price === query.price;
});
,这应该为您工作:
var activevars = [\'fill\',\'price\'];
var activeattributes = [\'down\',\'low\'];
var pillowSelection = $.grep(data.pillow,function(a) {
var ret = false;
for (var i = 0,il = activevars.length; i < il; i++) {
if ($.inArray(a[activevars[i]],activeattributes) > -1) {
ret = true;
}
}
return ret;
});
,这就是我解决问题的方式:
var array1 = [1,2,3,4,5],array2 = [5,1,6];
function compareArrays(arr1,arr2) {
return $(arr1).not(arr2).length == 0
};
然后在每个循环的a中运行此命令:
var hasValues = compareArrays(array1,array2) ? \'true\' : \'false\');
if(hasValues == true){
// show content
}else{
// Hide content
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。