Jquery数组对象 – 如何将后缀变量添加到索引名称
我有这个数组对象,它启动每个索引:
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 };
但它导致: Uncaught SyntaxError: Unexpected token +
有任何想法吗?
以下是另一种可能适合您的方法:
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)属性都可以单独访问,如下所示:
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})
添加新密钥并删除旧密钥
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);
输出: Object {hours0: 0, overtime0: 0, income0: 0, expenditure0: 0}