javascript / jQuery에 isset of php와 같은 것이 있습니까?
이 질문에 이미 답변이 있습니다.
- JavaScript isset () 해당 20 답변
javascript / jQuery에 변수가 설정 / 사용 가능한지 여부를 확인하는 것이 있습니까? PHP에서는 이와 isset($variable)
같은 것을 확인 하는 데 사용 합니다.
감사.
이 표현을 시도하십시오 :
typeof(variable) != "undefined" && variable !== null
이는 변수가 정의되고 null이 아닌 경우 true이며, 이는 PHP의 isset 작동 방식과 동일합니다.
다음과 같이 사용할 수 있습니다.
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
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:
typeof(variable) !== "undefined"
checks if the variable is defined at allvariable !== 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)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
}
'IT박스' 카테고리의 다른 글
동등성이 제대로 작동하도록하려면 구조체에서 무엇을 재정의해야합니까? (0) | 2020.10.29 |
---|---|
Mac 가상 키 코드 목록은 어디에서 찾을 수 있습니까? (0) | 2020.10.29 |
Django + Postgres : "현재 트랜잭션이 중단되고 트랜잭션 블록이 끝날 때까지 명령이 무시됩니다." (0) | 2020.10.29 |
Angular에서 2 개의 모델을 하나의 입력 필드에 바인딩하는 방법은 무엇입니까? (0) | 2020.10.29 |
파이썬 프로그램을 실행 가능하게 만들기 위해 Linux에서 무엇을 사용합니까? (0) | 2020.10.29 |