开发者

javascript custom array search prototype got some problems

I create an array search prototype

Array.prototype.searchRE = function(searchStr) {   
    var returnArray = false;   
    for (i in this) { 
      if (typeof(searchStr) == 'object') {
        if (searchStr.test(this[i])) { 
          if (!returnArray) {returnArray = []} 
          returnArray.push(i);
        }
      } else {
        if (this[i] === searchStr) {
          if (!returnArray) {returnArray = []}
          returnArray.push(i);
        }
      }   
    }  
    return returnArray;
}

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

result1=mycars.searchRe(/bm/i);   // return 2 
result2=mycars.searchRe(/b/i);    /开发者_JAVA百科/ return 0,2,searchRe
result3=mycars.searchRe(/m/i);    // return 2

My questions is no 2, why it returns "searchRe"? the function name?


That happens because you are traversing you array with the for-in statement, and this statement enumerates inherited properties (as your searchRe function).

The purpose of the for-in statement is to enumerate object properties, to traverse arrays a sequential loop is always recommended.

...<snip>...

Edit: Ok, since you are handling other properties than "array indexes" in your array objects, you should check that the properties you enumerate are own, non-inherited:

//...
for (var i in this) { // <- notice `var i`, otherwise `i` will be global
  if (this.hasOwnProperty(i)) { // the property physically exist on the object
    //..
  }
}
//..

Edit 2: You will have problems detecting when the argument is a RegExp object.

In Chrome, there is a syntax extension that allows you to "call" a RegExp object just like it were a function, Firefox allows this also, but in Chrome the real problem is that the typeof operator returns "function" instead the expected "object" result, for example:

var re = /a/;
re('a');   // equivalent to call re.exec('a');

typeof re; // "function" on Chrome, "object" in other implementations

So, instead checking:

//..
if (typeof searchStr == 'object') {
  //...
}
//..

I would recommend you at least:

if (searchStr && searchStr.test) {
  //...
}

Or:

if (searchStr && typeof searchStr.test == 'function') {
  //...
}

Or:

if (Object.prototype.toString.call(searchStr) == '[object RegExp]') {
  //...
}


It is because you are using an associative array loop (for i in this), which when applied to an object will loop over the properties and methods too. In this case you are adding a "searchRE" method to the array, which qualifies it in the loop. Change your loop to a normal for loop.

for(var i = 0; i < this.length; i++) {

}

I have a blog post about js loops: http://slappyza.wordpress.com/2010/10/03/fast-loops-in-javascript/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜