在JavaScript中使用动态变量名称

孤人 提交于 2020-03-16 15:31:12

某厂面试归来,发现自己落伍了!>>>

在PHP中,您可以执行以下令人惊奇/可怕的事情:

$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1

有没有办法用Java做类似的事情?

例如,如果我有一个var name = 'the name of the variable'; 如何获得名称为name的变量的引用?


#1楼

他们的意思是不,你不能。 没有办法完成它。 所以有可能你可以做这样的事情

function create(obj, const){
// where obj is an object and const is a variable name
function const () {}

const.prototype.myProperty = property_value;
// .. more prototype

return new const();

}

具有与ECMAScript 5中实现的功能相同的创建功能。


#2楼

eval()在我的测试中不起作用。 但是可以向DOM树添加新的JavaScript代码。 因此,这是一个添加新变量的函数:

function createVariable(varName,varContent)
{
  var scriptStr = "var "+varName+"= \""+varContent+"\""

  var node_scriptCode = document.createTextNode( scriptStr )
  var node_script = document.createElement("script");
  node_script.type = "text/javascript"
  node_script.appendChild(node_scriptCode);

  var node_head = document.getElementsByTagName("head")[0]
  node_head.appendChild(node_script);
}

createVariable("dynamicVar", "some content")
console.log(dynamicVar)

#3楼

在Javascript中,您可以使用所有属性都是键值对的事实。 jAndy已经提到了这一点,但是我不认为他的回答表明了如何利用它。

通常,您不是试图创建一个变量来保存变量名,而是试图生成变量名然后使用它们。 PHP使用$$var表示法来做到这一点,但是Javascript不需要这样做,因为属性键可以与数组键互换。

var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);

给出123。通常您要构造变量,这就是为什么存在间接的原因,因此您也可以采用其他方法。

var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);

#4楼

只是不知道一个糟糕的答案会得到这么多的选票。 答案很简单,但您会使它变得复杂。

// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000;  // in a function we use "this";
alert(article_count);

#5楼

这是一个例子:

for(var i=0; i<=3; i++) {
    window['p'+i] = "hello " + i;
}

alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3

另一个例子 :

var myVariable = 'coco';
window[myVariable] = 'riko';

alert(coco); // display : riko

因此, myVariable的值“ coco ”成为变量coco

因为全局作用域中的所有变量都是Window对象的属性。

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