JavaScript : 정의되지 않음! == 정의되지 않음?
참고 : ECMAScript5.1, 섹션 15.1.1.3에 따라 window.undefined는 읽기 전용입니다.
- 최신 브라우저는이를 올바르게 구현합니다. 예 : Safari 5.1, Firefox 7, Chrome 20 등
- Undefined는 여전히 Chrome 14, ...에서 변경할 수 있습니다.
나는 최근에 통합 할 때 페이스 북 연결을 함께 Tersus , 나는 처음에 오류 메시지 수신 Invalid Enumeration Value
및 Handler already exists
페이스 북의 API 함수를 호출 할 때를.
문제의 원인은
object.x === undefined
'object'에 속성 'x'가 없으면 false를 반환합니다.
두 개의 Facebook 함수에서 엄격한 평등을 정규 평등으로 대체하여 문제를 해결했습니다.
FB.Sys.isUndefined = function(o) { return o == undefined;};
FB.Sys.containsKey = function(d, key) { return d[key] != undefined;};
이것은 나를 위해 일하게 만들었지 만 Facebook의 JavaScript 코드와 내 코드 간의 충돌을 암시하는 것 같습니다.
원인은 무엇입니까?
힌트 : undefined == null
while undefined !== null
. 이것은 여기서 문제가 아닙니다. 문제는 우리가 얻는 방법 undefined !== undefined
입니다.
문제는 ==를 사용하는 null에 비해 undefined가 true를 제공한다는 것입니다. 따라서 undefined에 대한 일반적인 검사는 다음과 같이 수행됩니다.
typeof x == "undefined"
이렇게하면 변수 유형이 실제로 정의되지 않습니다.
window.undefined를 원하는대로 설정할 수 있으므로 object.x !== undefined
object.x가 실제 정의되지 않은 경우 얻을 수 있습니다. 제 경우에는 실수로 undefined를 null로 설정했습니다.
이를 확인하는 가장 쉬운 방법은 다음과 같습니다.
window.undefined = null;
alert(window.xyzw === undefined); // shows false
물론 이런 일은 일어나지 않을 것입니다. 제 경우에는 버그가 조금 더 미묘했으며 다음 시나리오와 동일했습니다.
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
undefined
초보자가 모를 수도있는 에 대한 중요한 정보를 게시하고 싶습니다 .
다음 코드를보십시오.
/*
* Consider there is no code above.
* The browser runs these lines only.
*/
// var a;
// --- commented out to point that we've forgotten to declare `a` variable
if ( a === undefined ) {
alert('Not defined');
} else {
alert('Defined: ' + a);
}
alert('Doing important job below');
변수가를 a
사용하여 선언 된 var
적이없는 이 코드를 실행 하면 ERROR EXCEPTION이 표시되고 놀랍게도 경고가 전혀 표시되지 않습니다.
'아래에서 중요한 작업 수행'대신 스크립트가 예기치 않게 종료되어 맨 첫 줄에 처리되지 않은 예외가 발생합니다.
다음은 이러한 목적으로 설계된 키워드 undefined
사용 여부를 확인하는 유일한 방탄 방법입니다 typeof
.
/*
* Correct and safe way of checking for `undefined`:
*/
if ( typeof a === 'undefined' ) {
alert(
'The variable is not declared in this scope, \n' +
'or you are pointing to unexisting property, \n' +
'or no value has been set yet to the variable, \n' +
'or the value set was `undefined`. \n' +
'(two last cases are equivalent, don\'t worry if it blows out your mind.'
);
}
/*
* Use `typeof` for checking things like that
*/
이 방법은 가능한 모든 경우에서 작동합니다.
사용하는 마지막 인수 undefined
는 이전 버전의 Javascript에서 잠재적으로 덮어 쓸 수 있다는 것입니다 .
/* @ Trollface @ */
undefined = 2;
/* Happy debuging! */
내가 충분히 명확 했길 바랍니다.
==
대신 같음 연산자 를 사용하는 것은 좋지 않습니다 ===
.
undefined === undefined // true
null == undefined // true
null === undefined // false
은 object.x === undefined
반환해야 true
하는 경우 x
알 수없는 속성입니다.
In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:
If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.
In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:
value = myObject[name]; if (value === undefined) { alert(name + ' not found.'); }
From - JQuery_Core_Style_Guidelines
Global Variables:
typeof variable === "undefined"
Local Variables:
variable === undefined
Properties:
object.prop === undefined
var a;
typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true
A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.
B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined
wherever you are.
In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.
참고URL : https://stackoverflow.com/questions/776950/javascript-undefined-undefined
'developer tip' 카테고리의 다른 글
gradle의 versionNameSuffix에 날짜 빌드를 추가하는 방법 (0) | 2020.11.16 |
---|---|
프록시 뒤의 dockerfile에서`apt-get`을 어떻게 실행합니까? (0) | 2020.11.16 |
Android Eclipse 플러그인 : Instrumentation Test Runner가 지정되지 않음 (0) | 2020.11.16 |
상태 표시 줄의 높이? (0) | 2020.11.16 |
Android 서비스는 항상 실행되어야 함 (일시 중지 또는 중지하지 않음) (0) | 2020.11.15 |