1

It must be that I'm missing something big here. For some reason .charAt(i) returns undefined in this piece of code.

Demo

    let images = {};
    let alphabet = 'abcdefghijklmnopqrstuvwxyz';
    let imageArray = ['a', 'b', 'c', 'd'];
    for (let i = 0; i < imageArray.length; i++){
        let letter = alphabet.charAt[i]; // returns undefined
        images[letter] = imageArray[i];
    }

    console.log(images); // {undefined: "d"}

4 Answers 4

3

You need a function call of String#charAt

alphabet.charAt(i);
//             ^ ^

instead of a property accessor with brackets.

let images = {};
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
let imageArray = ['a', 'b', 'c', 'd'];
for (let i = 0; i < imageArray.length; i++) {
  let letter = alphabet.charAt(i); // returns undefined
  images[letter] = imageArray[i];
}

console.log(images); // {undefined: "d"}

Sign up to request clarification or add additional context in comments.

Comments

2

There's an error in your syntax! You want to call the alphabet.charAt function, of course. But you're doing charAt[i] instead of charAt(i). Square brackets are the syntax for accessing a property of an array/object by a variable (i), so you end up getting a property of the function charAt - for example charAt[0]. But that doesn't exist, so it just evaluates to undefined.

So, to fix this, just replace the square brackets (charAt[i]) with parentheses (charAt(i)). You always use parentheses to call a function, not square brackets.

Comments

1

You have to call the .charAt() function as a function like .charAt(i) instead of .charAt[i]

Comments

0

Here is it!, alphabet.charAt() is function, not array. change [] to () and it starts to work.

let images = {};
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
let imageArray = ['a', 'b', 'c', 'd'];
for (let i = 0; i < imageArray.length; i++){
    let letter = alphabet.charAt(i); // returns undefined
    images[letter] = imageArray[i];
}

console.log(images); // {undefined: "d"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.