JQuery / Javascript : var 존재 여부 확인
중복 가능성 :
JavaScript에 변수가 정의되어 있는지 어떻게 확인할 수 있습니까?
JavaScript에서 null, 정의되지 않은 또는 빈 변수를 확인하는 표준 함수가 있습니까?
두 부분으로 발생하는 스크립트가 있습니다.
첫 번째 부분은 var를 설정합니다.
var pagetype = "textpage";
두 번째 부분은 간단한 if 문입니다.
if(pagetype == "textpage") {
//do something
};
이제 두 번째 부분 인 if 문이 내 사이트의 모든 페이지에 나타납니다. 그러나 var가 선언 된 첫 번째 부분은 일부 내 페이지에만 나타납니다.
var가없는 페이지에서는 자연스럽게이 오류가 발생합니다.
Uncaught ReferenceError: pagetype is not defined
그래서 내 질문은 : JavaScript 또는 JQ를 사용하여 var가 존재하는지 감지하는 방법이 있습니까 (데이터가 할당 된 경우뿐만 아니라)?
나는 다른 if 문을 사용할 것이라고 상상하고 있습니다.
if ("a var called pagetypes exists")....
나는 이와 같은 많은 답변이 있다고 생각하지만 여기에 있습니다.
if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
...
}
다음을 사용할 수 있습니다 typeof.
if (typeof pagetype === 'undefined') {
// pagetype doesn't exist
}
귀하의 경우에는 다른 모든 elclanrs답변 의 99.9 % 가 정답입니다.
하지만 undefined유효한 값 이기 때문에 누군가 초기화되지 않은 변수를 테스트한다면
var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true
var가 존재하는지 확인하는 유일한 100 % 신뢰할 수있는 방법은 예외를 포착하는 것입니다.
var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}
하지만 나는 결코 이런 식으로 쓰지 않을 것입니다
존재 여부를 테스트하는 방법에는 두 가지가 있습니다.
ㅏ. "property" in object
이 메서드는 속성이 있는지 프로토 타입 체인을 확인합니다.
비. object.hasOwnProperty( "property" )
이 메서드는 속성의 존재를 확인하기 위해 프로토 타입 체인을 올라가지 않으며 메서드를 호출하는 객체에 있어야합니다.
var x; // variable declared in global scope and now exists
"x" in window; // true
window.hasOwnProperty( "x" ); //true
다음 표현식을 사용하여 테스트하는 경우 false를 반환합니다.
typeof x !== 'undefined'; // false
각 조건문 앞에 다음과 같이 할 수 있습니다.
var pagetype = pagetype || false;
if (pagetype === 'something') {
//do stuff
}
It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:
if (typeof varName == 'undefined')
do not tell you if varName is a variable in scope, only that testing with typeof returned undefined. e.g.
var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true
In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in:
var global = this;
...
'bar' in global; // false
But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.
The solution is to always declare variables in an appropriate context.
- The global object isn't really a variable object, it just has properties that match global variables and provide access to them so it just appears to be one.
참고URL : https://stackoverflow.com/questions/13944100/jquery-javascript-check-if-var-exists
'program story' 카테고리의 다른 글
| 외부 스크립트가로드되었는지 확인 (0) | 2020.11.23 |
|---|---|
| Fragment # setRetainInstance (boolean)를 사용하는 이유는 무엇입니까? (0) | 2020.11.23 |
| 두 개체가 한 줄로 선언 된 경우 어떤 순서로 구성됩니까? (0) | 2020.11.23 |
| 메서드에서 익명 유형을 반환하는 방법이 있습니까? (0) | 2020.11.23 |
| Java의 WeakHashMap 및 캐싱 : 값이 아닌 키를 참조하는 이유는 무엇입니까? (0) | 2020.11.23 |