Javascript 动态jQuery变量名

Javascript 动态jQuery变量名,javascript,jquery,arrays,variables,Javascript,Jquery,Arrays,Variables,我希望获取li ID属性的值(它将是一个用户ID),并将其作为字符串的一部分使用,最终将其作为变量名的一部分使用。我将使用这个变量名创建一个数组 我了解基本知识,但似乎无法找到jQuery/javascript的正确组合来实现这一神奇 jQuery('#user-list li').click(function() { var userID = jQuery(this).attr("id"); // i want to add the word array to the end

我希望获取li ID属性的值(它将是一个用户ID),并将其作为字符串的一部分使用,最终将其作为变量名的一部分使用。我将使用这个变量名创建一个数组

我了解基本知识,但似乎无法找到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);

});

您可以在全局
窗口
对象中存储变量:

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);
});
事实上,每个未在闭包中声明的
var x
声明变量
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);
});

它在这里起作用:

你可以这样做

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

使用对象保存各种用户数组:

window.userData = {};

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

    alert(window.userData[userID][0].startTime);
}
但是,您可能不想将
userData
对象存储在全局名称空间中;为了防止意外的名称冲突,您至少应该将其放在自己的命名空间中。

尝试
eval

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

不能用这种方法创建数组。当您按原样调用数组构造函数时,它返回新的空数组,
var theVariableName
的值因此被重写,您只能具有动态属性,而不能具有动态变量。也就是说,为什么需要一个动态变量?我认为没有必要这样做。这听起来像是吹毛求疵,但你问题的标题有点不对劲。它是动态JavaScript变量名,而不是jQuery。jQuery使操作DOM变得更容易,它与核心编程逻辑无关。我有朋友说“我不知道如何编写JavaScript,但我知道如何编写jQuery”。如果你真的认真对待发展,你就不应该像他们那样。永远不要真正了解事物如何运作的基本结构会让你的生活充满压力和不满足感。JavaScript是一种很棒的语言,值得努力学习这是一个真正懒惰的
eval
用法。此外,这将(可能)在事件处理程序的本地名称空间中创建变量,这不太可能有用。-1:这不是使用eval的好理由,而且这在将来的JS版本中不起作用,因为JS版本取消了将通过eval创建的变量添加到当前上下文的支持。