在jquery

时间:2017-10-25 06:49:33

标签: javascript jquery arrays

我的脚本中有一些动态生成的数组,如下所示:

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']);

请帮我从数组中获取价值。

3 个答案:

答案 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'])