2

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

Array.prototype.push = function(){   

if(condition){

   //execute push if true

  }

  else
  {

    //return false

  }

}

帮我如何编码?这会影响我代码中的所有数组。我只想在推送时检查特定数组的这种情况。有什么方法可以实现?

4

1 回答 1

2

jsFiddle:http: //jsfiddle.net/QhJzE/4

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

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

这里有一些很棒的信息: http: //perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/。我在这里展示的内容在那篇文章中称为“直接扩展”。

于 2013-04-04T06:05:13.020 回答