以下是我的首選項,按我的偏好排序。性能,如果真的相關,你應該基準。偏好取決於你的代碼和目的。
// If independent and appropriate, split it into two separate functions
// modularization into smaller reusable building blocks is good
var calcAFunction = function() {
var calcA = ...
return calcA;
}
var calcBFunction = function() {
var calcB = ...
return calcB;
}
// Returning an array
var calcFunction = function() {
var ar = [];
var calcA = ...
ar.push(calcA);
var calcB = ...
ar.push(calcA);
return ar;
}
// Returning an object, disadvantage you must maintain key names as opposed to index
var calcFunction = function() {
var o = {};
var calcA = ...
o.key1 = calcA;
var calcB = ...
o["key2"] = calcB;
return o;
}
// Calling it with a callback function
var calcFunction = function(cb) {
var o = {};
var calcA = ...
var calcB = ...
cb(calcA, calcB)
}
calcFunction(function(A, B) {})
UPDATE
// Returning an object, disadvantage you must maintain key names as opposed to index
var calcFunction = function() {
var o = {};
var calcA = ...
o.key1 = calcA;
var calcB = ...
o["key2"] = calcB;
return o;
}
var retObj = calcFunction();
//you can access retObj.key1 and retObj.key2
我怎麼叫這個,如果它是'的問題o [ 「鍵2」] = CALCB;'路,我需要CALCB價值? – user3101259
@ user3101259我剛剛補充說明了兩種方法可以在對象上設置按鍵。你可以通過_o.key2_或_o。[「key2」] _來訪問返回對象。當你的鍵名有空格時,後一種語法非常有用,例如_o。[「with space」] _(_o.with space_將不起作用) – cbayram
我的意思是整行..'var foo = calcFunction(o 。[「key2」]);'? – user3101259