Javascript Jquery数组对象-如何向索引名添加后缀变量
我有一个启动每个索引的数组对象:Javascript Jquery数组对象-如何向索引名添加后缀变量,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一个启动每个索引的数组对象: var example = { 'hours': 0, 'overtime': 0, 'income': 0, 'expenditure': 0 }; 但是,它位于.each()循环中。每个索引都需要一个唯一的标识符,如:hours0hours1 我用来附加后缀的旧格式非常庞大 example['hours' + index] = 0; example['overtime' + index] = 0; example['income'
var example = { 'hours': 0, 'overtime': 0, 'income': 0, 'expenditure': 0 };
但是,它位于.each()
循环中。每个索引都需要一个唯一的标识符,如:hours0
hours1
我用来附加后缀的旧格式非常庞大
example['hours' + index] = 0;
example['overtime' + index] = 0;
example['income' + index] = 0;
example['expenditure' + index] = 0;
我试过以下方法
var example = { 'hours'+index: 0, 'overtime'+index: 0, 'income'+index: 0, 'expenditure'+index: 0 };
但它会导致:未捕获的语法错误:意外的令牌+
有什么想法吗?添加新密钥并删除旧密钥
var example = {
'hours': 0,
'overtime': 0,
'income': 0,
'expenditure': 0
};
var index = 0;
for (var key in example) {
example[key + index] = example[key];//adding new key with old value
delete example[key];//delete old key
}
console.log(example);
输出:
对象{hours0:0,overtime0:0,income0:0,expenditure0:0}
以下是一种可能适合您的替代方法:
var employee = [];
var numEmpl = 100; // total number of employees
for(var i = 0; i < numEmpl; i++)
employee[i] = {'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0};
或者,您可以一次更新给定员工的所有信息,如下所示:
employee[20].overtime = 10;
console.log(employee[20].overtime) // => 10
employee[30] = {'hours' : 45, 'overtime' : 5, 'income' : 1000, 'expenditure' : 0}
console.log(employee[30].overtime) // => 5
要添加新员工,只需执行以下操作:
employee.push({'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0})
杰拉尔德的回答肯定是最好的办法 但是请注意,也可以将字符串表达式作为对象字段内联计算。以下是您的操作方法:
let a = { ['foo' + 'bar' + 123]: 5 }
// a is now { foobar123: 5 }
使用括号是正确的方法实际上我不认为还有其他方法可以做到这一点,也许你可以定义
e=example
,然后e['hours'+index]=0;等等。
最后,example=e
您必须使用括号表示法-要获得完整的解释,请参见感谢各位,我听说这绝对是一种更好的方法!