$("#submit").click(function(event) {
event.preventDefault()
var data = [{"date_range": $("#date").val()},
{"day_of_week": $("#day_of_week").find('option:selected').text()},
{"call_volume": $("#call_volume").find('option:selected').text()},
{"number_of_calls": $("#number_of_calls").val()}]
var info = data.filter(function(item) {return $.isEmptyObject(item)})
alert(info)
})
上面的代码有什么问题?
基本上我想做的是过滤数据数组中不为空的对象。
我的意思是某些东西通过 filter
的标准应该是正确的吧?
那么为什么上面的代码不起作用?
尽管数据数组中的大多数对象不为空,但警报信息始终为空
最佳答案
尝试否定$.isEmptyObject(object)
的结果,
var info = data.filter(function(item) {return !$.isEmptyObject(item)});
因为,如果传递的对象不是空对象,那么 isEmptyObject
将返回 false
,而您在 callBack
中返回它过滤器
。所以数组中的所有元素都被忽略了。
这就是 Array.prototype.filter
的工作原理,
var keepIt = true;
var sample = [1,2,3,4].filter(function(){
return keepIt; //It will be true always,
//so all the items will be preserved.
//If it is false, then all the elements will be ignored.
});
关于javascript - 为什么 $.isEmptyObject 在这里无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35811130/