开发者

Issue with pushing values to a javascript array if it is a function

I am trying to create a set of buttons that behave like a list, where an array is created from the values selected.

Below is the function for checking if the value already exists in the array, and if it does not it will not add the new value.

function linearSearch(arrayName, sValue) 
{               
    Array.prototype.exists = function(search){
      for (var i=0; i<this.length; i++)
        if (this[i] == search) return tru开发者_如何转开发e;

      arrayName.push(sValue);
      return false;
    } 
}

Here is the jquery click function (of the listed items) where this function is called:

    con_array = [];
    $('.con_button').live('click', function (e) {
        e.stopPropagation()                              
        $(this).html('<div class="fun_button_center"></div>');
        con_value = $(this).attr('data-value');
        linearSearch(con_array, con_value);
        alert(con_array);
    });

The function works perfectly fine if it is inside of the click function without parameters. Yet in this circumstance, where it would be optimal because I can reuse it, no value is displayed with alert(con_array);


At the very least, write your `linearSearch function this way:

function linearSearch(arrayName, sValue) 
{               
    Array.prototype.exists = function(search){
      for (var i=0; i<this.length; i++)
        if (this[i] == search) return true;
    };

    if (arrayName.exists(sValue) return true;

    arrayName.push(sValue);
    return false;     
}

It's brittle to monkey-patch Array this way, though, so you can either monkey-patch it at global scope (still ugly, but at least it's both faster and available everywhere:

Array.prototype.exists = function(search){
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return true;
};

function linearSearch(arrayName, sValue) 
{    
    if (arrayName.exists(sValue) return true;

    arrayName.push(sValue);
    return false;     
}

Or you can just inline that loop:

function linearSearch(arrayName, sValue) 
{    
    for (var i=0; i<arrayName.length; i++)
      if (arrayName[i] == sValue) return true;

    arrayName.push(sValue);
    return false;     
}


You can try like this:

Array.prototype.exists = function(search){
      for (var i=0; i<this.length; i++)
        if (this[i] == search) return true;

      this.push(search);
      return true;
} 

function linearSearch(arrayName, sValue) 
{               
    arrayName.exists(sValue);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜