动态jQuery变量名称

我想获取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); }); 

使用Object来保存各种用户数组:

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

您可能不希望将userData对象存储在全局命名空间中; 为了防止意外的名称冲突,您至少应该将它放在您自己的命名空间中。

您可以在全局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); }); 

事实上,每个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); }); 

它在这里工作: http : //jsfiddle.net/bingjie2680/NnnRk/

你可以这样做..

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

试试eval

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