Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to number array elements outputs "undefined"

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?

like image 812
Anish Gupta Avatar asked May 16 '26 05:05

Anish Gupta


2 Answers

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.

like image 172
Jason Avatar answered May 18 '26 19:05

Jason


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.

like image 43
Šime Vidas Avatar answered May 18 '26 18:05

Šime Vidas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!