简体   繁体   中英

Unexpected behaviour of hasOwnProperty

I'm writing a function which checks if an object contains keys like 'id' or 'serif:id'. Unfortunately this doesn't work properly.

function returnIdPreferSerifId(object) {
    if (object.hasOwnProperty('serif:id' === true)) {
        return object['serif:id'];
    } else if (object.hasOwnProperty('id' === true)) {
        return object.id;
    } else {
        console.log(object)
        console.log(object.hasOwnProperty('serif:id' === true))
        console.log(object.hasOwnProperty('id' === true))
        throw `ID not found in Layer 1!`;
    }
}

The test object is:

{ 
  id: 'ska',
  d: 'M255.848,145.321l19.839,0.054l12.677,8.62l6.085,-8.62l-8.62,-29.41l-30.488,13.637l0.507,15.719Z',
  style: 'fill:rgb(187,222,251);stroke:white;stroke-width:1.33px;' 
}

I expect the function to return 'ska' as it is the objects id. Instead the console shows

false
false

path\to\module\modules\svgHandler.js:135
        throw `ID not found in Layer 1!`;
        ^
ID not found in Layer 1!

Thanks for your help in advance!

You've got your parentheses in the wrong place:

if (object.hasOwnProperty('serif:id' === true))

should be

if (object.hasOwnProperty('serif:id') === true)

and you could drop the === true if you like

if (object.hasOwnProperty('serif:id'))

object.hasOwnProperty('serif:id' === true) will evaluate like below.

object.hasOwnProperty(false)
false //if false is not key of object.

You should move === false outside the ()

if (object.hasOwnProperty('serif:id') === true)

Or you don't need to compare something with true in if statement.

if (object.hasOwnProperty('serif:id'))

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