Dava Davilion
Dava Davilion

Reputation: 11

Undefined arrays

I've been working on a website when I had a javascript problem I made an empty array and then added the following script.

  while(e<=f){
        array[0]=array[0]+x.charAt(e);
        e++;
        console.log(array[0]);
    }

I get the same value that I want but the word "undefined" with it

Upvotes: 0

Views: 66

Answers (2)

yanai edri
yanai edri

Reputation: 369

If you made the array like that

new Array(100)

then a[1] will return you undefined because this is an array of 'empty' - try to make your array like this

const a = Array.from({length: 100}, (item, index)=> index)

with the map function as the second argument

Upvotes: 0

David
David

Reputation: 218827

If array is initially empty, then array[0] is initially undefined. So this operation:

array[0]+x.charAt(e)

will produce "undefined" concatenated with some value.

You can conditionally use an empty string when array[0] is undefined, for example:

(array[0] || '') + x.charAt(e)

Upvotes: 3

Related Questions