Contrôle JavaScript si la variable existe (est définie/initialisée)

Mots clés : javascriptvariablesinitializationundefinedjavascript

meilleur 5 Réponses Contrôle JavaScript si la variable existe (est définie/initialisée)

vote vote

92

if (typeof variable !== 'undefined') {     // the variable is defined } 
vote vote

81

if (typeof variable === 'undefined') {     // variable is undefined } 
if (typeof variable === 'undefined' || variable === null) {     // variable is undefined or null } 
vote vote

80

if (elem) { // or !elem 
if(elem) {  if(typeof elem === 'string' && elem.trim()) { /// 
vote vote

67

if (typeof v === "undefined") {    // no variable "v" is defined in the current scope    // *or* some variable v exists and has been assigned the value undefined } else {    // some variable (global or local) "v" is defined in the current scope    // *and* it contains a value other than undefined } 
if ("v" in window) {    // global variable v is defined } else {    // global variable v is not defined } 
vote vote

56

elem != null 
if (elem === undefined) ... 
var undefined; // really undefined if (elem === undefined) ... 
(function (undefined) {     if (elem === undefined) ... })(); 

Questions similaires