IT박스

javascript / jQuery에 isset of php와 같은 것이 있습니까?

itboxs 2020. 10. 29. 07:56
반응형

javascript / jQuery에 isset of php와 같은 것이 있습니까?


이 질문에 이미 답변이 있습니다.

javascript / jQuery에 변수가 설정 / 사용 가능한지 여부를 확인하는 것이 있습니까? PHP에서는 이와 isset($variable)같은 것을 확인 하는 사용 합니다.

감사.


이 표현을 시도하십시오 :

typeof(variable) != "undefined" && variable !== null

이는 변수가 정의되고 null이 아닌 경우 true이며, 이는 PHP의 isset 작동 방식과 동일합니다.

다음과 같이 사용할 수 있습니다.

if(typeof(variable) != "undefined" && variable !== null) {
    bla();
}

PHP JS의 JavaScript isset ()

function isset () {
    // discuss at: http://phpjs.org/functions/isset
    // +   original by: Kevin van     Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // +   improved by: Rafał Kukawski
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    var a = arguments,
        l = a.length,
        i = 0,
        undef;

    if (l === 0) {
        throw new Error('Empty isset');
    }

    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false;
        }
        i++;
    }
    return true;
}

typeof는 내가 생각하는 목적에 부합 할 것입니다.

if(typeof foo != "undefined"){}

속성이 있는지 확인하려면 hasOwnProperty를 사용하는 것이 좋습니다.

그리고 대부분의 개체는 다른 개체의 속성 (결국 개체로 이어지는)이므로 window값이 선언되었는지 확인하는 데 적합합니다.


당연히 아닙니다 ... 그러나 인터넷 검색 결과 http://phpjs.org/functions/isset:454


http://phpjs.org/functions/isset:454

phpjs 프로젝트는 신뢰할 수있는 소스입니다. 거기에서 사용 가능한 많은 js 동등한 PHP 기능. 나는 오랫동안 사용해 왔고 지금까지 문제를 발견하지 못했습니다.


문제는 정의되지 않은 변수를 함수에 전달하면 오류가 발생한다는 것입니다.

이것은 인자로 전달하기 전에 typeof를 실행해야 함을 의미합니다.

이 작업을 수행하는 가장 깨끗한 방법은 다음과 같습니다.

function isset(v){
    if(v === 'undefined'){
        return false;
    }
    return true;
}

용법:

if(isset(typeof(varname))){
  alert('is set');
} else {
  alert('not set');
}

이제 코드가 훨씬 더 간결하고 읽기 쉽습니다.

다음과 같이 인스턴스화되지 않은 변수에서 변수를 호출하려고하면 여전히 오류가 발생합니다.

isset(typeof(undefVar.subkey))

따라서 이것을 실행하기 전에 객체가 정의되어 있는지 확인해야합니다.

undefVar = isset(typeof(undefVar))?undefVar:{};

여기 :)

function isSet(iVal){
 return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false

in addition to @emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").


Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.

// isset helper function 
var isset = function(variable){
    return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}

Here is a usage example of how to use it:

var example = 'this is an example';
if(isset(example)){
    console.log('the example variable has a value set');
}

It depends on the situation you need it for but let me break down what each part does:

  1. typeof(variable) !== "undefined" checks if the variable is defined at all
  2. variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
  3. variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case

Hope this helps someone :)


You can just:

if(variable||variable===0){
    //Yes it is set
    //do something
}
else {
    //No it is not set
    //Or its null
    //do something else 
}

참고URL : https://stackoverflow.com/questions/4231789/is-there-something-like-isset-of-php-in-javascript-jquery

반응형