對象屬性可以通過點符號,或支架符號(如陣列)被分配
因此,嘗試這個代替:
此[名稱] =名;
您不會得到部門名稱的「變量」,但部門數組將以部門爲屬性的對象。這是你想要的,如果部門名稱永遠是唯一的,你可能不需要該廁所的數組。
更新
要在我的觀點擴大上述關於非需要額外的數組。因爲你正在處理(我假設)獨特的部門名稱,這些可能是關鍵。
所以:
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);
}
後者梅託德才會開始到意義,如果輸入數據是更廣泛的或通過對象的功能需要的任何處理。對於我所說的例子來說,這可能是過度的。
東西它是值得的,它有時是值得不使用「名稱」作爲atrribute因爲它可以是一個保留字。並不總是一個問題,但可能會導致難以調試線路上的問題。 http://www.quackit.com/javascript/javascript_reserved_words.cfm – Jonathon 2013-02-18 16:18:11
謝謝你的提高,我改變了它。 – 2013-02-18 16:33:08