jQuery的Array对象 - 如何后缀变量添加到索引名 [英] Jquery Array Object - How to add suffix variable to index names

查看:202
本文介绍了jQuery的Array对象 - 如何后缀变量添加到索引名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动的每个索引此数组对象:

I have this array object which initiates each index:

var example = { 'hours': 0, 'overtime': 0, 'income': 0, 'expenditure': 0 };

然而,它是一个。每()循环中。每个索引需要像一个唯一的标识符: hours0 小时1

However it is inside a .each() loop. Each index needs a unique identifier like: hours0 hours1.

这我用于追加后缀旧的格式是庞大的。

The old format that I used to append a suffix is bulky.

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 };

但结果是:未捕获的SyntaxError:意外的令牌+

什么想法?

推荐答案

下面是可以做到这一点可能会为你工作的另一种方法:

Here's an alternate way to do this that might work for you:

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};

&NBSP;

以上code为您提供了一个对象数组,每个员工。每个对象(员工)财产可以单独访问是这样的:

The above code gives you an array of objects, one for each employee. Each object (employee) property can be accessed individually like this:

employee[20].overtime = 10;

console.log(employee[20].overtime) // => 10

&NBSP;

另外,你可以一次这样的更新对于给定员工的所有信息:

Alternately, you can update all info for a given employee at one time like this:

employee[30] = {'hours' : 45, 'overtime' : 5, 'income' : 1000, 'expenditure' : 0}

console.log(employee[30].overtime) // => 5

&NBSP;

要添加一个新员工,只要做到这一点:

To add a new employee, simply do this:

employee.push({'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0})

这篇关于jQuery的Array对象 - 如何后缀变量添加到索引名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆