在 JavaScript 中从数组中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8154326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get data from array in JavaScript
提问by Frederik Witte
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?
现在我想为数组中的一个数据分配一个新变量。假设我想将“88%”放在另一个变量中。我怎么做?
回答by Wladimir Palant
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.
cardData[0]
是您的数组,其索引为 0 的元素是另一个数组,并且"88%"
是该数组中索引为 6 的条目。
Of course you need to fix the syntax error in your code first as noted by pimvdb.
当然,您需要首先修复代码中的语法错误,如 pimvdb 所述。
回答by Alex Turpin
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.
然后,您可以使用括号表示法访问它的元素。它的索引从 0 开始。
var note = array[3]; //88%
回答by Emil Ivanov
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];