2

I want to add only integers and ignore others in a particular array. I want to add this condition on that array's push event.

Array.prototype.push = function(){   

if(condition){

   //execute push if true

  }

  else
  {

    //return false

  }

}

Help me how to code this? This affects all the array in my code. I want to check this condition on push only for a particular array. what are the ways to achieve it?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Gowsikan
  • 5,571
  • 8
  • 33
  • 43
  • 2
    You certainly shouldn't add it to the prototype. Rather, just create some special container class for this array that does the check for you. – Evan Trimboli Apr 04 '13 at 05:52

1 Answers1

2

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

Add the method directly to the array:

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);

(See How do I check that a number is float or integer? for isInt function.)

Here's some great information: http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/. What I've shown here is called "direct extension" in that article.

Community
  • 1
  • 1
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109