我們知道 中括號[] 可以取一個對象的屬性值,而且中括號里面還能是表達(dá)式
var obj = {a: 1}
var prop = 'a';
console.log(obj[prop]); // a
問題來了,中括號可以取任何變量的屬性值?
var exampe = 1;
example['1'] //undefined
example = true;
example['1'] //undefined
example = '';
example['1'] //undefined
example = null
example['1'] // 拋出異常
example = undefined
example['1'] // 拋出異常
說明了,[]可以為 任何分配內(nèi)存的變量 取屬性值
舉個例子:
為應(yīng)付后端數(shù)據(jù)不穩(wěn)定的問題,我們需要格式化的取出數(shù)據(jù),
需求,寫一個格式化函數(shù), 這個函數(shù)第一個參數(shù)為一個變量,類型不定,后面的參數(shù)為不定個數(shù)的屬性
比如:
formate(obj,, b, c, d) // obj.a.b.c.d
function formate() {
var args = Array.prototype.slice.call(arguments);
var obj = args[0];
var props = args.slice(1);
for (var i = 0; i < props.length; i++) {
// 這里必須要判斷, 不然的話 obj為null 或者 undefined
// 那么obj['x']會報(bào)錯
// 即[]只能去有分配內(nèi)存的變量的屬性值
if (obj) {
obj = obj[props[i]];
}
}
return obj;
}
var obj = {
a: {
b: {
c:{
d: 1
}
}
}
}
console.log(formate(obj, 'a', 'b', 'c'));
console.log(formate(null, 'a', 'b', 'c'));
console.log(formate(1, 'a', 'b', 'c'));