Get variable name in jQuery [closed]

不打扰是莪最后的温柔 提交于 2020-01-11 12:59:07

问题


How can I get the name of a variable?

Let's say I have an empty variable:

var myvariable;

How can I get the variable name so that this:

alert(this_is_what_i_am_looking_for);

will display:

myvariable

EDIT:

Maybe I am overcomplicating things. My real problem is that I have this two variables:

var firstVariable;
var secondVariable;

And I want to create a third variable that literally has this name:

var firstVariablesecondVariable;

EDIT2:

Thank for the answers, too much information, I have to look at them thoroughly.

This is what I have:

<div></div>
<div></div>
<div></div>

var i = 0;
var q = 0;

$('div').each(function() {
    var qi;
    i++;
});​

So I want to create three varaibles: var 00;var 01;var 02; Then I will load more divs with ajax and do:

q++;
i=0;

so when I apply the each function the second time I have three more variables: var 10;var 11;var 12;


回答1:


Variables names are identifiers and you cannot "ask" for an identifier what its name is. What you can do is create a new variable with the contents of the identifier, like this:

 var var1 = "variable1";
 var var2 = "variable2";

 // this will create an property/variable "variable1variable2" 
 // on the global namespace.
 window[var1 + var2] = "xyz";

 var content = variable1variable2; // content = xyz;



回答2:


Maybe you could use a hashtable to map name to values. Finally the name barFoo with value barFooTest is added in the hashtable.

var o = { bar: 'barTest' };
o.foo = 'fooTest';

var prevKey = '';
for(key in o)
{   
    prevKey = prevKey + '' + key ;
    alert(key + ': ' + o[key]);
}

o[prevKey] = "barFooTest";



回答3:


this is not possible, what you could do is work with a json object:

var myvars = {
   'firstVariable': 1,
   'secondVariable': 2,
   'firstVariablesecondVariable': function() { return this['firstVariable'] + this['secondVariable']; }
};


console.log(myvars['firstVariable'+'secondVariable']());
​

run code

For edit

var elements = [];
var myformat = function(n) { return (String(n).length == 1 ? '0' : '') + n; }
$('div').each(function(i, el) {
    elements.push(myformat(i));
});

console.log(elements);
​
// response ["00", "01", "02"] 

run code

Edit II

but if you want set values to variables, you can try this:

var elements = {}; // <- object
var myformat = function(n) {
    return (String(n).length == 1 ? '0' : '') + n;
}
$('div').each(function(i, el) {
    elements[myformat(i)] = el;
});

console.log(elements);​

Object
00: HTMLDivElement
01: HTMLDivElement
02: HTMLDivElement

run code



来源:https://stackoverflow.com/questions/12238540/get-variable-name-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!