-
Notifications
You must be signed in to change notification settings - Fork 18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js]对象属性检索 #18
Comments
Object.prototype.hash = function(attr) {
return attr && attr.split('.').reduce(function(pre, next) {
return pre && pre[next];
}, this);
};
var a = {
a: {
b: {
c: 1
}
}
}
a.hash('a.b.c') |
Object.prototype.hash = function() {
var firstTime = true,
ary,
deep,
cursor = 1,
buf;
return function(p) {
if(firstTime) {
ary = p.split('.');
deep = ary.length;
}
if((!firstTime && (cursor === deep)) || (deep === 1)) {
firstTime = true;
cursor = 1;
return this[p];
}
var _p = firstTime ? ary.shift() : p;
if(!this[_p]) {
firstTime = true;
cursor = 1;
return false;
}
buf = this[_p];
firstTime && (firstTime = false);
cursor++;
return arguments.callee.call(buf ,ary.shift());
}
}.call(); |
2333,来个简单有趣直接的~ Object.prototype.hash = function(attr){
var obj = this;
try{
return new Function('obj', 'return obj.'+ attr)(this);
}catch(e){
return undefined
}
}; 我这个比较简单,但是使用了 |
@VaJoy @LittleBearBond 提个问题, 假如这种情况呢? var o = {
a: {
b : false;
}
}
o.hash('a.b') |
@inJs 那就返回 |
Object.prototype.hash = function(attr){
if(!attr || attr.length === 0){
return (this.toString() === '[object Object]') ? this : this.toString();
}
if(toString.call(attr) === '[object String]'){
attr = attr.split('.');
}
return this.hash.call(this[attr.shift()],attr);
}; |
@VaJoy 66666666 |
我建议专门做一个代码出题的网站。 |
Object.prototype.hash = function (attr) {
let attrArr = attr.split('.')
let res = this
for (let i = 0, l = attrArr.length; i < l; i++) {
if (res[attrArr[i]] === undefined) {
return undefined
} else {
res = res[attrArr[i]]
}
}
return res
} 比较直白的解法... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
判断对象是否存在某属性,若有则返回属性值,否则返回
undefined
The text was updated successfully, but these errors were encountered: