gpt4 book ai didi

javascript - 如何检查 x 是否是对象而不是字符串对象

转载 作者:行者123 更新时间:2023-11-28 18:24:57 25 4
gpt4 key购买 nike

到目前为止我所拥有的。

const isNotNullObject = function (x) {
return (typeof x === "object" && x !== null);
};

它适用于数组和对象。但对于 String 对象也是如此!

isNotNullObject(String(5))
false
isNotNullObject(new String(5))
true

对于任何类型的字符串,我想要的是 false。请注意,我无法控制调用代码。我自己无法删除new。我需要一个解决方案,它不会创建一个新的字符串,只是为了检查是否相等(如果可能的话)出于性能原因。

最佳答案

使用instance of

return (typeof x === "object" && !(x instanceof String) && x !== null)

const isNotNullObject = function(x) {
return (typeof x === "object" && !(x instanceof String) && x !== null);
};

console.log(
isNotNullObject(String(5)),
isNotNullObject(new String(5))
)

关于javascript - 如何检查 x 是否是对象而不是字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334422/

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