问题描述
我看到这个堆栈溢出一些其他职位,但答案似乎总是创建具有键/值对的对象。这似乎并没有什么,我需要在我目前的状况。就是我想要做的:我有这有可能包含用户名不同的阵列。我要检查每个数组,看看用户名是present作为它们的值。如果是,我想一个字符串重数组变量的名字presentation。例如:
VAR阵列= ['苹果','橙','葡萄'];
VAR数组2 = ['苹果','鸭梨','垂直']member_arrays =新的Array();
//我想这一块是在动态我没有指定数组名称
//在inArray或member_arrays [member_arrays.length + 1](通过我的阵列只循环
//添加一个字符串重数组名到member_arrays数组presentation)
如果($ .inArray(苹果,数组)!= -1)
member_arrays [member_arrays.length] ='阵';
如果($ .inArray(苹果,数组2)!= -1)
member_arrays [member_arrays.length] ='数组2';
//等等...
您不能这样做,在JavaScript中。这就是为什么人们建议使用一个对象,并保持你的变量作为对象的属性。
顺便说一句,当你追加到一个数组,你只想长度,不长+ 1:
member_arrays [member_arrays.length] ='阵';
数组是从零开始,所以下一个插槽总是长度值。
的修改的—好了,还有哪里可以做一个案例:当你的变量是全球性的。任何命名为x的全局变量也可以被称为窗口(用于在Web浏览器code)对一个属性:
VAR X = 3;
警报(窗口['X']); //警报3
请避免全局变量用于此目的: - )
I've seen a few other posts about this on Stack Overflow, but the answer always seems to be to create an object with key / value pairs. This doesn't seem to be what I need in my current situation. What I'm wanting to do: I have different arrays which could possibly contain a username. I want to check each array and see if the username is present as a value in them. If it is, I'd like a string representation of a name of the array variable. Example:
var array = ['apple', 'orange', 'grape'];
var array2 = ['apple', 'pear', 'plumb']
member_arrays = new Array();
// I'd like this block to be dynamic in that i don't have to specify the array name
// in the inArray or member_arrays[member_arrays.length+1] (just loop through my arrays
// and add a string representation of the array name to the member_arrays array)
if ($.inArray( 'apple', array ) != -1)
member_arrays[member_arrays.length] = 'array';
if ($.inArray( 'apple', array2) != -1)
member_arrays[member_arrays.length] = 'array2';
// etc...
You cannot do that in JavaScript. That's why people suggest using an object and keeping your "variables" as properties in the object.
By the way, when you're appending to an array, you want just the length, not length + 1:
member_arrays[member_arrays.length] = 'array';
Arrays are zero-based, so the "next" slot is always the "length" value.
edit — well, there is a case where you can do that: when your variables are global. Any global variable named "x" can also be referred to as a property of "window" (for code in a web browser):
var x = 3;
alert(window['x']); // alerts "3"
Please avoid global variables for this purpose :-)
这篇关于在Javascript转换变量名字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!