Humble Dolt
Humble Dolt

Reputation: 970

Custom made javascript function(inheritence example)

How do I access array first element by custom made function which will work as a built in function like array.pop()?

Say if I have an array var arr=[1,2,3,4] and I want to have a function like arr.first() which will return me an array which will be having first element inside it like [1]

Upvotes: 0

Views: 43

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

 .slice(0,1)

or

 [ array[0] ]

i dont think theres a need for an inbuilt function.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190907

You can augment any array instance with Array.prototype.

Array.prototype.first = function() { return this[0]; };

However, it is strongly discouraged to modify the built in types.

Upvotes: 1

Related Questions