我的脚本中有一些动态生成的数组,如下所示:
var abc = {
'Lorem' = 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Why' = 'but also the leap into electronic typesetting',
'Where' = 'making it over 2000 years old.'
}
var def = {
'Lore' = 'Ipsum is simply dummy text of the printing and typesetting industry.',
'hy' = 'but also the leap into electronic typesetting',
'Whre' = 'making it over 2000 years old.'
}
var ghi = {
'Lrem' = 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Wh' = 'but also the leap into electronic typesetting',
'Were' = 'making it over 2000 years old.'
}
现在我需要从数组中获取值,我从用户动态获取数组的名称,并将其存储在array_name
之类的变量中。
我试图从像
这样的变量中获取价值var array_name = `abc`;
console.log(array_name['lorem']);
它给了我undefined
作为回复。另外,尝试将值存储在hidden field
并从textbox
获取值,但它对我不起作用:
console.log(($('#array_name').val()['lorem']);
请帮我从数组中获取价值。
答案 0 :(得分:1)
不要将array_name指定给字符串。
var abc = {
'Lorem': 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Why' : 'but also the leap into electronic typesetting',
'Where' : 'making it over 2000 years old.'
}
var def = {
'Lore': 'Ipsum is simply dummy text of the printing and typesetting industry.',
'hy' :'but also the leap into electronic typesetting',
'Whre' : 'making it over 2000 years old.'
}
var ghi = {
'Lrem' : 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Wh' : 'but also the leap into electronic typesetting',
'Were' : 'making it over 2000 years old.'
}
let new_name = abc
console.log(new_name['Lorem'])

答案 1 :(得分:1)
eval
,如果您的随机变量是全局范围的,您可以使用window[array_name]['Lorem']
访问它,否则如果它们被限制在函数内部或类似,我建议你使用不同的方法,比如
var randomVars = {};
randomVars.abc = {
'Lorem': 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Why' : 'but also the leap into electronic typesetting',
'Where' : 'making it over 2000 years old.'
}
randomVars.def = {
'Lore': 'Ipsum is simply dummy text of the printing and typesetting industry.',
'hy' :'but also the leap into electronic typesetting',
'Whre' : 'making it over 2000 years old.'
}
randomVars.ghi = {
'Lrem' : 'Ipsum is simply dummy text of the printing and typesetting industry.',
'Wh' : 'but also the leap into electronic typesetting',
'Were' : 'making it over 2000 years old.'
}
通过这种方式,您可以像randomVars[array_name]['Lorem']
答案 2 :(得分:0)
我建议您创建一个对象来保存对象abc,def,...
,然后可以使用Bracket notation使用字符串
let obj = {
abc: {
'Lorem': 'Ipsum is simply dummy text of the printing and typesetting industry.'
},
def: {
'Lore': 'Ipsum is simply dummy text of the printing and typesetting industry.'
},
ghi: {
'Lrem': 'Ipsum is simply dummy text of the printing and typesetting industry.'
}
}
console.log(obj['abc'])