简体   繁体   中英

First time Javascript Object alert

You can probably see what I want to do, but I dont know how.

function SetupCards() {
    var Cards =
    {
        "1Name": "value1",
        "1Suit": 1,
        "1Number": 2, 
        "1Active": 0
    };



alert( Cards.1Name );
}

Try using:

alert(Cards['1Name']);

because the first character of the object item begins with a number.

Your variable names should not start with a number. Fix them.

function SetupCards() {
    var Cards =
    {
        "Name": "value1",
        "Suit": 1,
        "Number": 2, 
        "Active": 0
    };



alert( Cards.Name );
}

SetupCards();

Instead of making a variable you can just return an object literal like this, but this is not my prefered way of making a constructor function:

function SetupCards () {
    return {
        "1Name": "value1",
        "1Suit": 1,
        "1Number": 2,
        "1Active": 0
    }
}

alert(SetupCards()['1Name']);

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM