简体   繁体   中英

Comparing String-properties of objects with "===" give a confusing result ! (or am I doing something wrong??)

I have an object, with some properties in it, and as I'm trying to compare a given string property of this object, waiting for the compared result is true I got false !

Adding an empty string to the property (create a new String) and give the result I was waiting for.

Cann somebody explain me why can't I compare Strings-properties of Objects directly without using a "modified-copy" of it?

(code verified on 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

The type of returnedExecutionValue is an array and not a string.

you can use typeof to check the type of any variable.

for example:

let x = []
typeof x // "object"

typeof (x+"")  // "string"

This is exactly what you are doing.

In your case, you could try it as

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

console.log(hohoho.testCallback_abc.abc.returnATestValue.returnedExecutionValue [0] === testString); // true (as both value and type are same)

OR

console.log(hohoho.testCallback_abc.abc.returnATestValue.returnedExecutionValue == testString); // true (as returnedExecutionValue is an array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM