JavaScript에서 null 또는 undefined는 언제 사용됩니까? [복제]
이 질문에는 이미 답변이 있습니다.
난 정말 자바 스크립트를 반환 할 때까지로 혼란 스러워요 null
나 undefined
. 또한 다른 브라우저가 다르게 반환하는 것처럼 보입니다.
당신은 몇 가지 예 전해 주 시겠어요 null
/를 undefined
반납 브라우저와 함께.
지금은 undefined
측면에서 분명하지만 여전히 100 % 명확하지 않습니다 null
. 빈 값과 비슷합니까?
예 : 값이 설정되지 않은 텍스트 상자가 있습니다. 이제 그 가치에 접근하려고 할 때 가치가 null
같 undefined
습니까?
한 DOM 방법은 getElementById()
, nextSibling()
, childNodes[n]
, parentNode()
등 수익률 null
(그러나 정의 된 값을 갖지 않는) 호출 노드 객체를 반환하지 않는 경우.
속성이 정의되어 있지만 참조하는 객체가 존재하지 않습니다.
이것은 평등을 테스트하고 싶지 않은 몇 가지 시간 중 하나입니다.
if(x!==undefined)
null 값의 경우 true
그러나 또는 if(x!= undefined)
중 하나가 아닌 값에 대해서는 참 (전용)입니다 .undefined
null
나는이 답변 중 일부가 모호하고 복잡하다는 것을 알았습니다. 이러한 것을 확실히 알아내는 가장 좋은 방법은 콘솔을 열고 직접 테스트하는 것입니다.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
따라서 이것은 JavaScript의 미묘한 미묘한 차이 중 하나입니다. 보다시피,의 값을 무시하여에 undefined
비해 다소 신뢰할 수 없게 만들 수 있습니다 null
. ==
연산자를 사용하면 내가 알 수있는 한 안정적으로 사용 null
하고 undefined
상호 교환 할 수 있습니다. 그러나 null
재정의 할 수없는 이점 때문에를 사용할 때 사용할 수 ==
있습니다.
예를 들어, variable != null
ALWAYS 경우 false를 반환 variable
IS는 동일하거나 null
또는 undefined
반면 variable != undefined
경우 false를 반환한다 variable
IS가 동일하거나 null
또는 undefined
하지 않는 한 undefined
IS 미리 재.
당신은 안정적으로 사용할 수 있습니다 ===
구분하는 연산자를 undefined
하고 null
당신이 값이 실제로 있는지 확인해야하는 경우, undefined
(대신 null
).
ECMAScript 5 사양에 따르면 :
- 모두
Null
와Undefined
유형에 내장 된 여섯이 있습니다.
4.3.9 정의되지 않은 값
변수에 값이 지정되지 않은 경우 사용되는 기본 값
4.3.11 null 값
객체 값이 의도적으로 없음을 나타내는 기본 값
다양한 시나리오에 대해 정의되지 않았습니다.
var로 변수를 선언하지만 절대 설정하지 마십시오.
var foo;
alert(foo); //undefined.
설정하지 않은 객체의 속성에 액세스하려고합니다.
var foo = {};
alert(foo.bar); //undefined
제공되지 않은 인수에 액세스하려고합니다.
function myFunction (foo) {
alert(foo); //undefined.
}
늑대가 다른 답변에 대한 의견에서 지적했듯이 값을 반환하지 않는 함수.
function myFunction () {
}
alert(myFunction());//undefined
A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object
and undefined is of type undefined
.
I should also note that null is valid in JSON but undefined is not:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
I might be missing something, but afaik, you get undefined
only
Update: Ok, I missed a lot, trying to complete:
You get undefined
...
... when you try to access properties of an object that don't exist:
var a = {}
a.foo // undefined
... when you have declared a variable but not initialized it:
var a;
// a is undefined
... when you access a parameter for which no value was passed:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
... when a function does not return a value:
function foo() {};
var a = foo(); // a is undefined
It might be that some built-in functions return null
on some error, but if so, then it is documented. null
is a concrete value in JavaScript, undefined
is not.
Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable)
to test whether a value is set or not (both, null
and undefined
evaluate to false
).
Also different browsers seem to be returning these differently.
Please give a concrete example.
Regarding this topic the specification (ecma-262) is quite clear
I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm
I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.
I hope you find it useful.
A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.
This is a good article explaining the difference and also giving some examples.
참고URL : https://stackoverflow.com/questions/6429225/when-is-null-or-undefined-used-in-javascript
'IT박스' 카테고리의 다른 글
오류 : capybara-webkit 설치 오류 : (0) | 2020.07.21 |
---|---|
Git / GitHub를 사용하여 파일 삭제 (0) | 2020.07.21 |
Maven Repo에 Nexus 또는 Artifactory를 사용해야합니까? (0) | 2020.07.21 |
Chrome : 백그라운드 탭에서 시간 초과 / 간격이 일시 중지 되었습니까? (0) | 2020.07.20 |
3 개의 주요 C ++ 컴파일러에서 프로그램이 다르게 컴파일됩니다. (0) | 2020.07.20 |