将对象的字符串属性与"==="进行比较会得到一个令人困惑的结果!(还是我做错了什么??



我有一个对象,里面有一些属性,当我试图比较这个对象的给定字符串属性时,等待比较结果是真的,我得到了假!

向属性添加一个空字符串(创建一个新字符串)并给出我正在等待的结果。

有人可以解释为什么我不能直接比较对象的字符串属性而不使用它的"修改副本"吗?

(代码在 jsbin.com 上验证:https://jsbin.com/kojehinexe/edit?js,console)

var hohoho = {  "testCallback_abc": {
        "abc": {
            "addToNumber": {
                "executed": true,
                "returnedExecutionValue": [42]
            },
            "addToArray": {
                "executed": true
            },
            "addToObject": {
                "executed": true
            },
            "returnATestValue": {
                "executed": true,
                "returnedExecutionValue": ["testValue"]
            }
        }
    }
}
var testString = "testValue";
console.log(hohoho.testCallback_abc.abc.returnATestValue.returnedExecutionValue === testString); // return false
console.log(hohoho.testCallback_abc.abc.returnATestValue.returnedExecutionValue+"" === testString); // return true

returnedExecutionValue的类型是数组而不是字符串。

可以使用 TypeOf 检查任何变量的类型。

例如:

let x = []
typeof x // "object"
typeof (x+"")  // "string"

这正是您正在做的。

在您的情况下,您可以尝试将其作为

console.log(hohoho.testCallback_abc.abc.returnATestValue.returnedExecutionValue[0] === testString); 

console.log(hohoho.testCallback_abc.abc.returnATestValue.returnExecutionValue [0] === testString);//true (因为值和类型相同)

console.log(hohoho.testCallback_abc.abc.returnATestValue.returnExecutionValue == testString);//true (as returnExecutionValue 是一个数组)

相关内容

最新更新