0

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

3
  • what are the values of the variables? Commented Dec 8, 2022 at 20:42
  • 1
    Can you update this to a runnable minimal reproducible example which demonstrates the problem? Commented Dec 8, 2022 at 20:43
  • You have to add more information and example code for it to make sense to anyone Commented Dec 8, 2022 at 20:45

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.