最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavascriptJquery - .every() equivalent for operating on object - Stack Overflow

programmeradmin2浏览0评论

How can test over an object like the array.every() method? Trying to detect if all the terms in a query object are blank before sending it on. Obviously I could just write a little routine in a for loop, but I'm expecting there's a more succinct way of acplishing this.

// array - works
var queryArr = [ "", "" ];
if(!queryArr.every(function(el, i, arr) { return el == "" } )) {
    alert("nothing to search");
}

// object - "undefined is not a function"
var queryObj = { term1: "", term2: "" };
if(!queryObj.every(function(el, i, arr) { return el == "" } )) {
    alert("nothing to search");
}

How can test over an object like the array.every() method? Trying to detect if all the terms in a query object are blank before sending it on. Obviously I could just write a little routine in a for loop, but I'm expecting there's a more succinct way of acplishing this.

// array - works
var queryArr = [ "", "" ];
if(!queryArr.every(function(el, i, arr) { return el == "" } )) {
    alert("nothing to search");
}

// object - "undefined is not a function"
var queryObj = { term1: "", term2: "" };
if(!queryObj.every(function(el, i, arr) { return el == "" } )) {
    alert("nothing to search");
}
Share Improve this question asked Oct 31, 2014 at 19:41 robisrobrobisrob 96012 silver badges24 bronze badges 2
  • for in loop is the best – guramidev Commented Oct 31, 2014 at 19:45
  • There is no built in function, but it is easy to make one. – Karl-André Gagnon Commented Oct 31, 2014 at 19:53
Add a ment  | 

2 Answers 2

Reset to default 1

Map can be used call a function on each object in an array.

http://api.jquery./jquery.map/

You could implement your own every method this way:

Object.prototype.every=function(evalFunction){
    var self=this,
        property;

    if(typeof evalFunction!=='function')
        return evalFunction;

    for(property in self){
        if(self.hasOwnProperty(property) && !evalFunction(self[property], property, self)){
            return false;
        }
    }
    return true;
}

Then you could use the new every method on objects the same way you do with arrays
But if you only want to test this once on your code I sugest to use for in loop or robisrob's map solution

发布评论

评论列表(0)

  1. 暂无评论