我們知道 中括號(hào)[] 可以取一個(gè)對(duì)象的屬性值唾糯,而且中括號(hào)里面還能是表達(dá)式
var obj = {a: 1}
var prop = 'a';
console.log(obj[prop]); // a
問(wèn)題來(lái)了浆竭,中括號(hào)可以取任何變量的屬性值堡距?
var exampe = 1;
example['1'] //undefined
example = true;
example['1'] //undefined
example = '';
example['1'] //undefined
example = null
example['1'] // 拋出異常
example = undefined
example['1'] // 拋出異常
說(shuō)明了兆蕉,[]可以為 任何分配內(nèi)存的變量 取屬性值
舉個(gè)例子:
為應(yīng)付后端數(shù)據(jù)不穩(wěn)定的問(wèn)題,我們需要格式化的取出數(shù)據(jù)虎韵,
需求易稠,寫一個(gè)格式化函數(shù)包蓝, 這個(gè)函數(shù)第一個(gè)參數(shù)為一個(gè)變量,類型不定测萎,后面的參數(shù)為不定個(gè)數(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']會(huì)報(bào)錯(cuò)
// 即[]只能去有分配內(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'));