0

I have an object that looks like this:

var set_1 = {
    id: 'set_1',
    nameofSet : 'English fruits',
    category: 'languages',
    cards : [
        {
            front : 'apple',
            back : 'jablko'
        },
        {
            front : 'orange',
            back : 'pomarancza'
        },
        {
            front : 'pear',
            back : 'gruszka'
        }
    ]
}

Now there's a function:

$('#chooseSet').on('click', '.setName', function() {
    var setName = this.getAttribute("data-set-name");
    editCards(setName);
});

This is the HTML:

<div class="setName" data-set-name="set_1">English fruits</div>

It gives the setName parameter to the editCards function that looks like this:

editCards(setName) {
    console.log(setName); // logs "set_1"
    console.log(setName.cards); // logs "undefined" - why?
    console.log(set_1.cards);  // logs the `cards` array from `set_1'.
    // code
}

It takes the setName parameter.

My question is - why doesn't the second console.log give me the cards' array as it does in the thirdconsole.log` example?

1
  • 1
    console.log(window[setName].cards) Commented May 4, 2017 at 10:45

1 Answer 1

4

Because any attribute's value is a string. So in your case data-set-name returns the string "set_1", which is not a reference to the variable set_1. If your set_1 variable is global, you should be able to do this instead -

console.log(window[setName].cards)

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

1 Comment

Thank you, it worked! I will accept your answer in a few minutes when it's possible.

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.