Javascript 如何将阵列推送更改为特定阵列?

Javascript 如何将阵列推送更改为特定阵列?,javascript,arrays,Javascript,Arrays,我只想添加整数,而忽略特定数组中的其他整数。我想在该数组的推送事件上添加此条件 Array.prototype.push = function(){ if(condition){ //execute push if true } else { //return false } } 帮我怎么编码?这会影响代码中的所有数组。我只想针对特定阵列在推送时检查此条件。实现它的方法是什么?jsiddle: 将方法直接添加到数组中: var nums = [

我只想添加整数,而忽略特定数组中的其他整数。我想在该数组的推送事件上添加此条件

Array.prototype.push = function(){   

if(condition){

   //execute push if true

  }

  else
  {

    //return false

  }

}
帮我怎么编码?这会影响代码中的所有数组。我只想针对特定阵列在推送时检查此条件。实现它的方法是什么?

jsiddle:

将方法直接添加到数组中:

var nums = [];

nums.push = function(n) {
    if (isInt(n))
        Array.prototype.push.call(this, n);
}

nums.push(2);
nums.push(3.14);
nums.push('dawg');

console.log(nums);
(有关isInt的
isInt
功能,请参阅。)


这里有一些很好的信息:。在那篇文章中,我在这里展示的是所谓的“直接扩展”。

您当然不应该将其添加到原型中。相反,只需为这个数组创建一些特殊的容器类来为您进行检查。