简体   繁体   English

如何使用文本输入中的字符串变量来引用同名的数组

[英]how can I use string variable from text input to refer to an array of the same name

I have a number of arrays in a javascript file The array that I want to use in my calculations is: 我在javascript文件中有许多数组我想在计算中使用的数组是:

 var planets_num = []

If I want to use a certain array, I simply use: 如果我想使用某个数组,我只需使用:

  arraytouse = planets_num

What I want to do is use an input: 我想要做的是使用输入:

 <input type="text" id="mynewtext" value="Enter array name to use">

and then a function to get the value of "mynewtext": 然后一个函数来获取“mynewtext”的值:

 function getnewform1 () {
 newtext=document.getElementById('mynewtext').value
 . . .
 }

let's say that the var newtext = "abc" I then want: 让我们说var newtext =“abc”然后我想:

 abc = planets_num

ie the values from the array abc to be placed in the planets_num array 即来自数组abc的值将被放置在planets_num数组中

Hope this makes sense 希望这是有道理的

TIA TIA

If planets_num is in global scope, you can also refer to it like this: 如果planets_num在全局范围内,您也可以像这样引用它:

arraytouse = window['planets_num'];

Variables on objects are also indexable values on that object by the same name. 对象上的变量也是该对象上的可索引值,名称相同。 For global scope variables, they're on the window object. 对于全局范围变量,它们位于window对象上。

So you could do something like this: 所以你可以这样做:

arraytouse = window[document.getElementById('mynewtext').value];

If the arrays aren't in global scope then you can organize them as properties on some object and reference that object in the same way: 如果数组不在全局范围内,那么您可以将它们组织为某个对象上的属性,并以相同的方式引用该对象:

arraytouse = objectOfArrays[document.getElementById('mynewtext').value];

@David answer is cleaner is more efficient, but here is an alternative with an eval : @David答案更清洁更有效,但这里有一个eval的替代方案:

var my_array = [];

$("button")[0].onclick = function()
{
    var input_text = $("input")[0].value;
    var array_input = eval(input_text);
}

The fiddle is here: 小提琴在这里:

http://jsfiddle.net/W3NW9/3/ http://jsfiddle.net/W3NW9/3/

Rather than creating global variables, you should consider using an object and properties: 您应该考虑使用对象和属性,而不是创建全局变量:

var data = {
  planets_num: [],
  another_arr:[]
}

Now you can do: 现在你可以这样做:

var arraytouse = data[document.getElementById('mynewtext').value];

but of course you should be writing robust code like: 但是你当然应该编写健全的代码,如:

var input = document.getElementById('mynewtext');

// Make sure an element was found before trying to access its value
var arraytouse = input && data[input.value];

// Make sure the value resolved to something truthy before
// trying to use it
if (arraytouse) {
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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