动态jQuery变量名称

4
我想获取 li 元素的 ID 属性值(它将是一个 userID),并将其作为字符串的一部分,最终我将用这个字符串作为变量名的一部分。我将使用这个变量名创建一个数组。
我理解基础知识,但好像找不到正确的 jQuery/javascript 组合来实现这个魔法。
jQuery('#user-list li').click(function() {
    var userID = jQuery(this).attr("id");

    // i want to add the word array to the end of userID
    var theVariableName = userID + "Array";

    // I want to use this variable to create an array
    var theVariableName = new Array();

    // I want to continue to use the name throughout my document
    theVariableName.push({startTime: 7, endTime: 10});

    alert(theVariableName[0].startTime);

});

你不能这样创建一个数组。当你像这样调用Array构造函数时,它会返回一个新的空数组,并且var theVariableName的值会被重写。 - Dmitry Koroliov
1
你只能拥有动态属性,而不是动态变量。话虽如此,为什么你想要一个动态变量呢?我并不认为有这个必要。 - pimvdb
1
这可能听起来有点挑剔,但是你的问题标题有点不准确。它是动态-JavaScript-变量名称,而不是jQuery。jQuery使操作DOM更容易,与核心编程逻辑无关。我有朋友说:“我不知道如何编写JavaScript,但我知道如何编写jQuery”。如果你真的认真对待开发,最好不要像他们那样。从未真正理解事物如何工作的基本结构将使您作为开发人员的生活充满压力和不充实感。JavaScript是一种很棒的语言,值得学习。=) - rybosome
4个回答

2
使用一个对象来保存各种用户数组:
window.userData = {};

$(...).click(function() {
    // ...
    window.userData[userID] = [];
    window.userData[userID].push({startTime:7, endTime:10});

    alert(window.userData[userID][0].startTime);
}

虽然你可能不想将userData对象存储在全局命名空间中,但为了防止意外名称冲突,你至少应该将其放置在自己的命名空间中。


1

您可以将变量存储在全局window对象中:

jQuery('#user-list li').click(function() {
    var userID = jQuery(this).attr("id");

    // i want to add the word array to the end of userID
    var theVariableName = userID + "Array";

    // I want to use this variable to create an array
    window[theVariableName] = new Array();

    // I want to continue to use the name throughout my document
    window[theVariableName].push({startTime: 7, endTime: 10});

    alert(window[theVariableName][0].startTime);
});

实际上,每个声明的变量x,如果没有在闭包中声明,都将驻留在全局对象中。然而,我建议您使用另一个全局对象,例如userStorageObject或类似的对象:
var userStorageObject = {};
jQuery('#user-list li').click(function() {
    var userID = jQuery(this).attr("id");

    // i want to add the word array to the end of userID
    var theVariableName = userID + "Array";

    // I want to use this variable to create an array
    userStorageObject[theVariableName] = new Array();

    // I want to continue to use the name throughout my document
    userStorageObject[theVariableName].push({startTime: 7, endTime: 10});

    alert(userStorageObject[theVariableName][0].startTime);
});

这里可以运行:http://jsfiddle.net/bingjie2680/NnnRk/


0

你可以像这样做。

var variable = "Array";
window[id+variable] = "value";

-2

尝试使用eval

var theVariableName = userID + "Array";
eval(theVariableName+"= new Array()");

这是一个非常懒惰的使用eval。此外,这将(可能)在事件处理程序的本地命名空间中创建变量,这很不可能有用。 - millimoose
1
-1: eval是邪恶的 - Zeta
2
不是使用eval的好理由,而且这在未来的JS版本中将无法工作,因为它们不支持将通过eval创建的变量添加到当前上下文中。 - rybosome

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接