Object.prototype.hash = function(string) {
var obj = this;
string.split(".").forEach(function(el) {
console.log(obj); // 为什么每次 obj 会改变呢?
try {
obj = obj[el];
}
catch(e) {
obj = undefined;
}
});
return obj;
}
// 测试用例
var obj = {
person: {
name: 'joe',
history: {
hometown: 'bratislava',
bio: {
funFact: 'I like fishing.'
}
}
}
};
console.log(obj.hash('person.name'));
console.log(obj.hash('person.history.bio'));
console.log(obj.hash('person.history.homeStreet'));
console.log(obj.hash('person.animal.pet.needNoseAntEater'));
发现每一次循环,obj都递减了层次。
回复 (4)
E
可能没理解到你的意图。不过obj改变难道不是因为这句:
obj = obj[el];
A
引用 eeandrew可能没理解到你的意图。不过obj改变难道不是因为这句:
@eeandrew 同问。。obj 不是被重新赋值了吗
A
楼主,我写了个库干这事:https://github.com/alsotang/ettr
T
引用 eeandrew可能没理解到你的意图。不过obj改变难道不是因为这句:
@eeandrew @alsotang 啊,没注意,对!是的,非常感谢! 最近通宵做题,有些迷糊了。
参与回复
登录后即可参与回复。登录