有更好的方法吗?
如果我这样做:
if(typeof someObject[bar][foo] == "function"){
// Do something
}
我收到someObject[bar][foo] is not an object
错误,如果someObject[bar]
不存在,则会引用bar
。这意味着代码假定您知道someObj[bar]
已定义。所以我的解决方案就是:
if(typeof someObj[bar] === "object"){
if(typeof someObject[bar][foo] == "function"){
// Do something
}
}
如果我们想要努力减少代码行并制作好的,干净的,可读的代码,那么看起来多余和丑陋。有没有更好的方法来做到这一点,而不必经过两个if
点?我意识到这不是什么大不了的事,但我想知道是否有更好的方法。
答案 0 :(得分:1)
if( someObject.bar && someObject.bar.foo && typeof someObject.bar.foo === "function" ){
...
}
或相同,但具有更好的可见性符号样式:
if( someObject.bar
&& someObject.bar.foo
&& typeof someObject.bar.foo === "function" ){
...
}
答案 1 :(得分:1)
我担心没有简单的解释。
在哪种环境/情况下,您期望对象有条件地行事?为了举例说明我使用的......先进先出......并试图在同一时间尽可能简单...
。[我需要一些编辑:s]
/**
* @description Get an object from a list of objects by searching for a key:value pair
* @param {Object} obj : -literal, json
* @param {String} val : the value you seek
* @param {String} key : the key
* @param {Boolean} isTypeComparison : if set to true, the key and value will be checked against it's type as well
*/
getObjectProperty: function (obj, val, key, isTypeComparison) {
var property, o;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === 'object') {
o = this.getObjectProperty(obj[property], val, key);
if (o) {
break;
}
} else {
// found a property which is not an object
if (isTypeComparison) {
if (property === key && obj[property] === val) {
// we got a match
o = obj;
break;
}
} else {
if (property == key && obj[property] == val) {
// we got a match
o = obj;
break;
}
}
}
}
}
return o || undefined;
},
要为您的问题添加某种价值,在上述所有这些循环中,您会看到一种期望的挣扎。我已使用此代码搜索附加到列表的ajax联系人列表。因此,您肯定需要编写更多代码来满足深度和信任要求。
答案 2 :(得分:1)
如果您对问题进行概括,那么您基本上都在询问是否可以验证某种“路径”。在一个对象中是合法的。我这样做的方法是使用一个函数来获取对象和所需的路径':
function has(obj, path){
var temp = obj;
var path = path.split('.');
for(var i = 0; i < path.length; i++){
if(temp[path[i]])
temp = temp[path[i]];//path still exists
else
return false;//path ends here
}
return true;//the whole path could be followed
}
此示例使用传递为&#39; bar.foo&#39;但你可以很容易地调整一个数组[&#39; bar&#39;,&#39; foo&#39;]或者说它是传入的可变数量的参数。
这会使你的榜样成为:
if(has(someObject, bar + '.' + foo)){
if(typeof someObject[bar][foo] == "function"){
// Do something
}
}
虽然这并没有特定地减少这个例子,但如果你有更长的搜索路径,这可能会大大减少if语句链接在一起。
您可以修改该函数,使其返回路径指定的值(如果存在)而不是true,这样您只需要处理一行:
function get(obj, path){
var temp = obj;
var path = path.split('.');
for(var i = 0; i < path.length; i++){
if(temp[path[i]] !== undefined)
temp = temp[path[i]];//path still exists
else
return undefined;//path ends here
}
return temp;//the whole path could be followed
}
if(typeof get(someObject, bar + '.' + foo) === 'function'){
//do something
}