jQuery-在每个循环中使用变量名来命名新变量

时间:2014-08-06 04:41:23

标签: jquery

我有一系列项目,我正在尝试根据每个数组的项目名称分配一个变量名称。例如,如果数组具有值:

var thearray = {};
thearray['0'] = 'car';
thearray['1'] = 'boat';
thearray['2'] = 'truck';

我想最终得到三个变量,名为car_output, boat_output, truck_output

它们都包含相同的数据。以下是我尝试这样做的方法:

$.each(thearray, function(index, value) { 
    var value+'_output' = 'stuff...'; // something not right
});

我试图命名每个变量的方式不对。有什么想法吗?

4 个答案:

答案 0 :(得分:1)

这应该可以解决问题。秘诀是像数组一样使用全局window对象,以便创建动态变量名。

var thearray = {};
thearray['0'] = 'car';
thearray['1'] = 'boat';
thearray['2'] = 'truck';

$.each(thearray, function(index, value) { 
    window[value+'_output'] = 'stuff...';
});

console.log(car_output); // "stuff..."

答案 1 :(得分:0)

你可以使用数组,

var user_types = ["car","boat","truck"];
var types = {};

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

console.log(types);

我希望这可以帮到你..

答案 2 :(得分:0)

尝试动态创建object以存储相关值,请不要使用window object来存储值,因为它是笨拙方式。

var thearray = {};
thearray['0'] = 'car';
thearray['1'] = 'boat';
thearray['2'] = 'truck';

var obj={};
$.each(thearray, function (index, value) {
    obj[value+"_output"]="stuff";
});

DEMO

答案 3 :(得分:0)

我认为这就是你想要的。它按你的意愿工作。

var user_types = ["car","boat","truck"];
var types = {};

$.each(user_types, function( index, value ){
  types[value+'_Output'] = value;
});

console.log(types);

请参阅jsfiddle链接http://jsfiddle.net/C23U8/1/

相关问题