对象属性可以通过点表示法或括号表示法(如数组)分配
所以试试这个:
这个[名称] = 名称;
然后,您将不会获得部门名称的“变量”,但部门数组将是具有部门作为属性的对象。这是您想要的吗,如果部门名称始终是唯一的,您可能不需要 Array for loo。
更新
扩展我上面关于不需要额外数组的观点。因为您正在处理(我假设)唯一的部门名称,所以这些可能是关键。
所以:
function buildDepartments() {
var departmentList = SpreadsheetApp.getActiveSpreadsheet().getRange('a1:c2').getValues(), // Assuming a 3 column list with, say: department name, department head, department deputy.
departments = {},
d;
for (d = 0; d < departmentList.length; d += 1) {
departments[departmentList[d][0]] = {head: departmentList[d][1], deputy: departmentList[d][2]};
}
// To recall the department details ... however many there are
Logger.log(departments['Math'].head); // Logs the head of the Math department
}
但是,不要将自己束缚在可能会随着时间而变化的键上,因为如果部门名称发生变化,那么进行更改会很麻烦。如果您“取消指定”对象,使用 ScriptDB 也会更容易。因此:
function buildDepartments() {
// Assuming a 3 column list with, say: name, head, deputy.
var departmentList = SpreadsheetApp.getActiveSpreadsheet().getRange('a1:c2').getValues(),
departments = [], // Now this an array
d;
for (d = 0; d < departmentList.length; d += 1) {
departments.push({
title: departmentList[d][0],
head: departmentList[d][1],
deputy: departmentList[d][2]
});
}
// To recall the department details ... however many there are
// Logs the head of the Math department by filtering the array to a single entry
Logger.log(departments.filter(function (d) { return d.title = 'Math'; })[0]);
}
在这一点上,为了让事情更直观地回忆一下,部门数组可以再次成为构造函数对象。因此:
function DepartmentList () {
var list = [];
this.addDepartment = function (dept) {
list.push({ title: dept[0], head: dept[1], deputy: dept[2] });
return this; // for chaining reasons, if you like.
}
this.getDepartment() = function(dept) {
var foundDepartment = list.filter(function (d) { return d.title = dept; });
return foundDepartment[0] || {}; // empty object if no department match
}
return list; // bare calls to the object returns the whole list
}
function buildDepartments () {
var departments = SpreadsheetApp.getActiveSpreadsheet().getRange('a1:c2').getValues(),
departmentList = new DepartmentList(), // Now this an object again
d;
departments.forEach( departmentList.addDepartment(entry) ); // Possible because GAS supports ECMAScript5
// To recall the department details ... however many there are
// Logs the head of the Math department
Logger.log(departmentList.getDepartment('Math').head);
}
只有当输入数据更广泛或需要对象函数进行任何处理时,后一种方法才会开始有意义。对于我所说的例子来说,这可能是矫枉过正。