简体   繁体   中英

Get data from array in JavaScript

I've created an array with the following code:

var cardData[0] = [
    [
        'Rumble Pack',
        'Robert Mugabe',
        0.2,
        0.7,
        21,
        RuleTypes.dictatorship,
        '88%',
        '45%',
        '\'The Jewel of Africa\', Zimbabwe, returning to the stone age. R.M. let a rabble led by Chenjerai \'Hitler\' Hunzwi murder white farmers at will. 25 % of Zimbabwians HIV-positive. Life expectancy fallen 16 yrs. under R.M.'
    ]
];

Now I want to assign a new variable to one of the datas in the Array. Let's say that I want to put the '88%' in another variable. How do I do that?

You write:

var dataField = cardData[0][0][6];

cardData[0] is your array, its element with index 0 is another array, and "88%" is the entry with index 6 in that array.

Of course you need to fix the syntax error in your code first as noted by pimvdb.

I don't think you understand how arrays work. To initialize an array, simply use the bracket notation:

var array = ["Foo", "Bar", "Test", "88%"];

You can then access it's elements by using the bracket notation. It's indexes start at 0.

var note = array[3]; //88%

Simply formatting the code gives you the answer.

var cardData    = [ [ 'Rumble Pack'
                    , 'Robert Mugabe'
                    , 0.2
                    , 0.7
                    , 21
                    , RuleTypes.dictatorship
                    , '88%'
                    , '45%'
                    , '\'The Jewel of Africa\'
                    , Zimbabwe, returning to the stone age. R.M. let a rabble led by Chenjerai \'Hitler\' Hunzwi murder white farmers at will. 25 % of Zimbabwians HIV-positive. Life expectancy fallen 16 yrs. under R.M.' 
                    ] 
                  ];

var eightyeight = cardData[0][6];

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