如何使用 jquery 创建动态变量

How to create dynamic variables using jquery?

本文关键字:动态 变量 创建 jquery 何使用      更新时间:2023-09-26

我希望动态创建一些jquery变量。在我的代码中,我有一个循环,我想用循环值创建一些变量。这是我的示例代码。

array=["student","parent","employee"]
$.each(user_types, function( index, value ){
  var value+"_type" // this is the type of variable i want to build.
})

我发现了关于评估函数的信息。该代码是这样的。

var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");
alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.

是否有任何其他方法,因为我已经阅读了在编码文件时不首选 eval 函数.js

每当发现自己在变量名称中使用变量时,您可能希望使用对象文字。创建带有大括号的对象 {} ,然后使用方括号表示法设置对象属性键:

var user_types = ["student","parent","employee"];
var types = {};
$.each(user_types, function( index, value ){
  types[value] = 'The value of dynamic variable, val';
});

JSFiddle

注意:您尚未标记它,但我假设因为您使用了正在使用jQuery each(),如果我错了,请纠正我。

首先,我必须说,我想不出你想这样做的任何理由。

如果确实需要在全局范围内拥有这些变量,则可以执行以下操作:

var array=["student","parent","employee"]
array.forEach(function(value){
  window[value+"_type"] = 'My value ' + value;
});
console.log(student_type);
console.log(parent_type);
console.log(employee_type);

如果您不希望全局范围内的变量,恐怕我不知道一个优雅的解决方案。

我使用array.forEach而不是你的jQuery循环,因为这个问题与jQuery完全无关,而且因为我认为你没有说足够的逻辑来做一个连贯的例子。

编辑:我应该明确指出,虽然创建的"变量"的行为与全局范围内的其他变量大致相同,但它们不是变量。以下是它们的区别:

// Difference 1: hoisting
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
var x = 5;
window[y] = 5;
console.log(x); // 5
console.log(y); // 5
// Difference 2: [[Configurable]] 
delete x;
delete y;
console.log(x); // 5
console.log(y); // ReferenceError: y is not defined

如果要在字符串中添加中间变量,可以执行以下操作:

var itemSelect: number = 1;
$(`#tab${this.itemSelect}-tab`).tab('show');
/* Result -> $(`#tab1-tab`).tab('show');  */
/* HTML */
<a id="tb1-tab"> </a>