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?

1
  • 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. Commented Apr 4, 2013 at 5:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.