Javascript shortcut to assign a true / false variable to a variable if an array element exists

I was hoping I could just set true / false to a variable if my element exists in an associative array.

I tried this -

var finalDisExist = stepsArray['stepIDFinal'];   

- of course, this does exactly what you might think (assigning an object to a variable.

But I'm sure I saw something close to this before, can someone tell me what I'm missing?

Thank! Todd

+3
source share
4 answers

Perhaps the fastest and best way is stepsArray.hasOwnProperty('stepIDFinal').

NB: DO NOT use 'stepIDFinal' in stepsArray, as this will check the whole prototype chain for your "hashmap" object and detect toStringamong others ...

+6

, ?

var finalDisExist = !!stepsArray['stepIDFinal'];

, (, undefined 0) true, - false - . , stepsArray['stepIDFinal'] null 0, finalDisExist false...

+2

You want to use stepsArray.hasOwnProperty("stepIDFinal")if I'm not mistaken.

+2
source

You mean

var finalDisExist = !!stepsArray['stepIDFinal'];

or maybe

var finalDisExist = "undefined" !== typeof stepsArray['stepIDFinal'];

?

+1
source

All Articles