检查变量是否以最佳,最快和最小的方式存在JavaScript和jQuery

问题描述 投票:1回答:3

大家好,我有一些jQuery-JavaScript代码,它由一些未定义的变量组成。

我尝试通过执行以下代码来跳过(undefined)错误:

if(typeof undefined_var !== "undefined"){
    /*My code is here*/
}else{
    /*create variable*/
    /*My code is here*/
}

但是问题是我有很多变量,我必须使用像这样的大代码:

if(typeof undefined_var1 !== "undefined" && typeof undefined_var2 !== "undefined" && typeof undefined_var3 !== "undefined" /* && more */ ){

并且它没有优化,我正在寻找比它更好的东西:

if(undefined_var1 && undefined_var2 && undefined_var3)

反正有吗?

javascript jquery variables undefined exists
3个回答
1
投票

您可以使用try and catch来跳过错误,并在发生这样的错误时做您想做的一切:

try {
    if(undefined_vars /* && more*/){

    }
} catch(err) {
    // err.message will return the undefined error and you can put your create variable here and than start your code here again

}

现在,即使您没有在代码前加var,const,let且没有出错,也可以拥有代码。


0
投票

在定义变量的任何时候,都将它们放到单个对象上,然后您要做的就是检查对象是否存在:

if (!window.myObj) {
  // Define properties:
  window.myObj = {
    prop1: 'val1',
    prop2: 'val2',
    // ...
  };
}
// proceed to use `window.myObj.prop1`, etc

0
投票

您可以创建一个包含所有这些变量的数组,然后创建一个将该数组作为参数的函数。然后,在函数内部,使用条件(if语句)遍历数组以确定是否有错误。例如arr.reduce((bln,myVar)=> typeof myVar ==='undefined'&& bln,true)。调用该函数,它将返回true或false,具体取决于是否未定义。

var _0;
var _1;
var _2 = 'not undefined';
var _3 = 'again not undefined';

const test0 = [_0, _1]; //should return true (contains undefined)
const test1 = [_2, _3]; //should return false (doesn't contain undefined)
const test2 = [_0, _1, _2, _3]; //should return true (contains undefined)

function containsUndefined(arr){
  //loop array to determine if any are undefined
  return arr.reduce((bln, myVar) => typeof myVar == 'undefined' && bln, true);
}

console.log('test0', containsUndefined(test0));
console.log('test1', containsUndefined(test1));
console.log('test2', containsUndefined(test2));
© www.soinside.com 2019 - 2024. All rights reserved.