I want to number each item in an Array, like this:
["hello", "hi", "hey"].number()
> ["1. hello", "2. hi", "3. hey"]
Here's my code:
Array.prototype.number = function () {
var tempNum = this;
for (i in this) {
tempNum[i] = tempNum[(i + 1)] + ". " + tempNum[i]
}
return tempNum;
}
But this is the output:
["hello", "hi", "hey"].number()
> ["undefined. hello", "undefined. hi", "undefined. hey"]
Why? How should I implement this and why is my code not working?
I think you want something like this:
for(var i=0, len = this.length; i<len; i++){
tempNum[i] = (i + 1) + ". " + tempNum[i];
}
you're using tempNum when you shouldn't be in the right side of your equation. The reason you're getting "undefined" is because at some point in your current equation you're getting an index outside of the length of your array.
The ES5 way:
Array.prototype.number = function () {
return this.map( function ( value, i ) {
return ( i + 1 ) + '. ' + value;
});
};
Live demo: http://jsfiddle.net/XSYTK/1/
You'll need to shim .map() for IE8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With