gpt4 book ai didi

javascript - 依赖对象类型检查 Javascript 似乎是多余的

转载 作者:行者123 更新时间:2023-11-29 19:30:00 25 4
gpt4 key购买 nike

有更好的方法吗?

如果我这样做:

    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 点?我意识到这没什么大不了的,但我想知道是否有更好的方法。

最佳答案

恐怕没有简单的解释。

您希望对象在哪种情况/情况下有条件地运行?举个例子,说明我使用什么……去高级……并试图同时尽可能简单……

  • 您是否正在遍历一整套类似对象的数组?
  • 您能否信任该对象,以便您已经知道会发生什么?
  • 不同数据类型的对象比较?

.[我需要一些编辑: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;
},

为了给您的问题增加某种值(value),在上面的所有这些循环中,您会看到与期望的斗争。我已经使用此代码搜索附加到列表的 ajax 联系人列表。因此,您肯定需要编写更多代码来满足深度和信任要求。

关于javascript - 依赖对象类型检查 Javascript 似乎是多余的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28487894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com