jQuery 中是否有等效的 eval()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15459044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:05:56  来源:igfitidea点击:

Is there an equivalent of eval() in jQuery?

jqueryeval

提问by user1448031

I am trying to create dynamic variables in jQuery. I tried using eval()and it seems to work fine but I don't think eval()is a jQuery function. Is there an equilvant of eval()in jQuery? See my code here: http://jsfiddle.net/3CXgy/

我正在尝试在 jQuery 中创建动态变量。我尝试使用eval()它似乎工作正常,但我认为eval()它不是 jQuery 函数。eval()jQuery 中有 equilvant吗?在此处查看我的代码:http: //jsfiddle.net/3CXgy/

var test = function(pos) {
    alert(eval('COUNT_'+pos));
}

var COUNT_LEFT = 20;
var COUNT_RIGHT = 30;
test('LEFT');
test('RIGHT');

Is there a different way to do this other than using eval()? I am not sure if eval()is perfectly fine in my example above.

除了使用之外,还有其他方法可以做到这一点eval()吗?我不确定eval()在我上面的例子中是否完全没问题。

回答by mplungjan

There are very rarely any reasons to use eval

很少有理由使用 eval

Here is your code assuming the vars were defined in the head

这是假设变量在头部定义的代码

var test = function(pos) {
    alert(window['COUNT_'+pos]);
}

var COUNT_LEFT = 20;
var COUNT_RIGHT = 30;
test('LEFT');
test('RIGHT');

To not pollute the global namespace, use

为了不污染全局命名空间,请使用

var COUNT = {"left":20, "right":30 }
var pos = "left";
alert(COUNT[pos]);

回答by Ohgodwhy

I'd personally prefer to just store it in an object which we can easily access, add to, modify, and remove from anytime.

我个人更喜欢将它存储在一个我们可以随时轻松访问、添加、修改和删除的对象中。

var count = {
    'left' : 20,
    'right' : 30
}

var test = function(pos){
    alert(count[pos]);
}

test('left');
test('right');

If you feel the need to use uppercase, just ensure you use a cohesive pattern, so switch it all to lowercase in the function.

如果您觉得需要使用大写字母,请确保使用有凝聚力的模式,因此在函数中将其全部切换为小写字母。

var test = function(pos){
    alert(count[pos.toLowerCase()]);
}

回答by Denys Séguret

To access a global variable by its name, use this notation :

要按名称访问全局变量,请使用以下表示法:

window['COUNT_'+pos]

Usually you'd want to have your variable held in an object :

通常,您希望将变量保存在一个对象中:

var obj = {
     COUNT_LEFT:20,
     COUNT_RIGHT:30
}

and then you may access the "variables" as obj['COUNT_'+pos].

然后您可以将“变量”作为obj['COUNT_'+pos].

Your question as it is written lets think you don't really see what's jQuery. jQuery is a library providing useful functions that you use from your JavaScript code. You can't program in jQuery : you program in JavaScript using JavaScript functions, some of them being taken in the jQuery library.

您写的问题让您认为您并没有真正了解什么是 jQuery。jQuery 是一个库,提供您从 JavaScript 代码使用的有用函数。你不能在 jQuery 中编程:你使用 JavaScript 函数在 JavaScript 中编程,其中一些被 jQuery 库采用。