null이 객체 인 이유는 무엇이며 null과 undefined의 차이점은 무엇입니까?
JavaScript에서 로 null
간주되는 이유는 무엇 object
입니까?
확인 중
if ( object == null )
Do something
같은
if ( !object )
Do something
?
그리고 또한:
null
과 의 차이점은 무엇입니까 undefined
?
(name is undefined)
당신 : 무엇입니까 name
? (*)
자바 스크립트 : name
? 무엇입니까 name
? 당신이 무슨 말을하는지 모르겠습니다. 당신은 name
전에 언급 한 적이 없습니다 . (클라이언트) 측에 다른 스크립팅 언어가 있습니까?
name = null;
당신 : 무엇입니까 name
?
자바 스크립트 : 모르겠어요.
간단히 말해서 undefined
사물의 개념이 존재하지 않는 곳입니다. 유형이 없으며 해당 범위에서 이전에 참조 된 적이 없습니다. null
존재하는 것으로 알려진 곳이지만 그 가치가 무엇인지는 알 수 없습니다.
기억해야 할 한 가지 즉 null
, 개념적,하지와 동일 false
또는 ""
그들이 타입 캐스팅, 즉 후 동일시하는 경우에도, 또는
name = false;
당신 : 무엇입니까 name
?
JavaScript : 부울 거짓.
name = '';
당신 : 무엇입니까 name
?
JavaScript : 빈 문자열
* : name
이 문맥에서 정의 된 적이없는 변수를 의미합니다. 정의되지 않은 변수 일 수 있지만 name은 거의 모든 HTML 양식 요소의 속성입니다. 이드보다 훨씬 먼저 제정 된 것이 었습니다. ID는 고유해야하지만 이름은 고유하지 않아도되므로 유용합니다.
차이점은 다음 스 니펫으로 요약 할 수 있습니다.
alert(typeof(null)); // object
alert(typeof(undefined)); // undefined
alert(null !== undefined) //true
alert(null == undefined) //true
확인 중
object == null
확인하는 것과 다릅니다 if ( !object )
.
! Boolean(object)
단항 !
연산자가 오른쪽 피연산자를 자동으로 부울로 캐스트 하기 때문에 후자는과 같습니다 .
Boolean(null)
false와 같기 때문에 !false === true
.
따라서 객체가 null 이 아니라 false 또는 0 또는 "" 인 경우 다음과 같은 이유로 검사가 통과됩니다.
alert(Boolean(null)) //false
alert(Boolean(0)) //false
alert(Boolean("")) //false
null
인 객체가 아닌 , 그것을 인 프리미티브 값 . 예를 들어 속성을 추가 할 수 없습니다. 때때로 사람들은 그것이 객체라고 잘못 가정 typeof null
합니다 "object"
. 그러나 이것은 실제로 버그입니다 (ECMAScript 6에서 수정 될 수도 있습니다).
차이 null
와 undefined
같은 다음이다 :
undefined
: JavaScript에서 사용되며 "값 없음"을 의미합니다. 초기화되지 않은 변수, 누락 된 매개 변수 및 알 수없는 변수에는 해당 값이 있습니다.> var noValueYet; > console.log(noValueYet); undefined > function foo(x) { console.log(x) } > foo() undefined > var obj = {}; > console.log(obj.unknownProperty) undefined
그러나 알 수없는 변수에 액세스하면 예외가 발생합니다.
> unknownVariable ReferenceError: unknownVariable is not defined
null
: 프로그래머가 "값 없음"을 나타 내기 위해 사용합니다 (예 : 함수에 대한 매개 변수).
변수 조사 :
console.log(typeof unknownVariable === "undefined"); // true
var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true
var bar = null;
console.log(bar === null); // true
일반적으로 JavaScript에서는 항상 ===를 사용하고 ==를 사용하지 않아야합니다 (== 는 예기치 않은 결과를 생성 할 수있는 모든 종류의 변환 을 수행 합니다 ). 검사 x == null
는 null
및 undefined
다음 모두에 대해 작동하기 때문에 가장자리 케이스입니다 .
> null == null
true
> undefined == null
true
변수에 값이 있는지 확인하는 일반적인 방법은 변수를 부울로 변환하고 값이 있는지 확인하는 것입니다 true
. 이 변환은 if
문과 부울 연산자에 의해 수행됩니다 ! ("아니").
function foo(param) {
if (param) {
// ...
}
}
function foo(param) {
if (! param) param = "abc";
}
function foo(param) {
// || returns first operand that can't be converted to false
param = param || "abc";
}
이 접근 방식의 단점 : 다음 값은 모두로 평가 false
되므로주의해야합니다 (예 : 위의 검사는 undefined
및을 구분할 수 없음 0
).
undefined
,null
- 부울 :
false
- 숫자 :
+0
,-0
,NaN
- 문자열 :
""
Boolean
함수 로 사용하여 부울로의 변환을 테스트 할 수 있습니다 (일반적으로와 함께 사용되는 생성자입니다 new
).
> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
null과 undefined의 차이점은 무엇입니까 ??
정의가없는 속성은 정의되지 않습니다. null은 개체입니다. 유형은 객체입니다. null은 "값 없음. undefined는 객체가 아니며 유형이 정의되지 않음을 의미하는 특수 값입니다.
변수를 선언하고 null로 설정할 수 있으며 "null"이 인쇄되고 "undefined"가 출력되는 것을 제외하고는 동작이 동일합니다. 정의되지 않은 변수를 null로 또는 그 반대로 비교할 수도 있으며 조건은 참이됩니다.
undefined == null
null == undefined
자세한 내용 은 null과 undefined의 JavaScript 차이점 을 참조하세요.
그리고 새로운 편집으로 예
if (object == null) does mean the same if(!object)
객체가 false 인 경우 테스트 할 때, 그들은 경우 테스트 할 때 모두에만 조건을 만족 거짓 ,하지만 때 진실
여기에서 확인하십시오 : Javascript gotcha
질문의 첫 부분 :
JavaScript에서 null이 객체로 간주되는 이유는 무엇입니까?
지금은 수정할 수없는 자바 스크립트 디자인 오류입니다. 유형 객체가 아니거나 null 유형이어야합니다. 실제 개체를 감지 할 때 추가 검사 (때로는 잊어 버림)가 필요하며 버그의 원인이됩니다.
질문의 두 번째 부분 :
if (object == null)
Do something
다음과 동일하게 확인 중입니다.
if (!object)
Do something
두 검사는 다음을 제외하고 항상 모두 거짓입니다.
개체가 정의되지 않았거나 null : 둘 다 true입니다.
객체가 원시이고 0,
""
또는 false : 첫 번째는 false이고 두 번째는 true입니다.
객체가 원시 객체가 아니라 실제 객체 (예 new Number(0)
: new String("")
, 또는 new Boolean(false)
)이면 두 검사가 모두 거짓입니다.
따라서 '객체'가 실제 객체를 의미하는 것으로 해석되면 두 검사는 항상 동일합니다. 프리미티브가 허용되는 경우 0 ""
,, 및 false에 대한 검사가 다릅니다 .
와 같은 object==null
경우에는 분명하지 않은 결과가 버그의 원인이 될 수 있습니다. 의 사용 ==
은 절대 권장되지 않으며 ===
대신 사용하십시오.
질문의 세 번째 부분 :
또한 :
null과 undefined의 차이점은 무엇입니까?
JavaScript에서 한 가지 차이점은 null은 object 유형이고 undefined는 undefined 유형이라는 것입니다.
JavaScript에서는 null==undefined
true이며 유형이 무시되면 동일한 것으로 간주됩니다. 왜 그렇게 결정했지만 0 ""
과 거짓은 같지 않습니다. 자의적인 의견 인 것 같습니다.
JavaScript에서는 null===undefined
유형이에서 동일해야하므로 true가 아닙니다 ===
.
실제로 null과 undefined는 모두 존재하지 않기 때문에 동일합니다. 따라서 0을 수행하고 ""
그 문제에 대해서도 빈 컨테이너 []
및 {}
. 너무 많은 유형의 똑같은 것은 버그를 만드는 방법입니다. 한 가지 유형 또는 전혀없는 것이 더 좋습니다. 가능한 한 적게 사용하려고합니다.
'false', 'true'및 '!' 예를 들어 단순화 할 수있는 또 다른 웜 가방이며, if(!x)
그 if(x)
자체만으로도 충분하므로 참과 거짓이 필요하지 않습니다.
선언 된 var x
것은 값이 주어지지 않으면 정의되지 않은 유형이지만 x가 전혀 선언되지 않은 것과 같아야합니다. 또 다른 버그 소스는 비어있는 빈 컨테이너입니다. 따라서 같이 선언하고 정의하는 것이 가장 좋습니다 var x=1
.
사람들은이 모든 종류의 아무것도 알아 내려고 빙글 빙글 빙빙 돌고 있지만, 복잡한 다른 옷을 입어도 똑같은 일입니다. 현실은
undefined===undeclared===null===0===""===[]==={}===nothing
그리고 아마도 모두 예외를 던져야합니다.
var x = null;
x는 null로 정의됩니다.
y는 정의되지 않았습니다. // 정의하지 않았기 때문에
if (!x)
null은 false로 평가됩니다.
null 및 undefined를 이해하는 한 가지 방법은 각각이 발생하는 위치를 이해하는 것입니다.
다음 상황에서 널 리턴 값을 예상하십시오.
DOM을 쿼리하는 메서드
console.log(window.document.getElementById("nonExistentElement")); //Prints: null
Ajax 요청에서받은 JSON 응답
{
name: "Bob",
address: null
}
유동적 상태에있는 새로운 기능. 다음은 null을 반환합니다.
var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));
// But this returns undefined:
Object.getOwnPropertyDescriptor({}, "a");
존재하지 않는 다른 모든 경우는 정의되지 않음으로 표시됩니다 (@Axel로 표시됨). 다음은 각각 "undefined"를 인쇄합니다.
var uninitalised;
console.log(uninitalised);
var obj = {};
console.log(obj.nonExistent);
function missingParam(missing){
console.log(missing);
}
missingParam();
var arr = [];
console.log(arr.pop());
물론 작성하기로 결정했다면 var unitialised = null; 또는 메서드에서 직접 null을 반환하면 다른 상황에서 null이 발생합니다. 그러나 그것은 매우 분명합니다.
세 번째 경우는 변수에 액세스하고 싶지만 변수가 선언되었는지조차 알지 못하는 경우입니다. 이 경우 typeof를 사용하여 참조 오류를 피하십시오.
if(typeof unknown !== "undefined"){
//use unknown
}
요약하면 DOM을 조작하거나 Ajax를 처리하거나 특정 ECMAScript 5 기능을 사용할 때 null을 확인합니다. 다른 모든 경우에 대해 엄격한 동등성으로 undefined를 확인하는 것이 안전합니다.
if(value === undefined){
// stuff
}
JavaScript의 다양한 null 검사 비교 :
http://jsfiddle.net/aaronhoffman/DdRHB/5/
// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;
...trim...
http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
Some precisions:
null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.
What happens in an if
goes as follows for if( o )
:
The expression in the parentheses o is evaluated, and then the if
kicks in type-coercing the value of the expression in the parentheses - in our case o
.
Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.
To add to the answer of What is the differrence between undefined
and null
, from JavaScript Definitive Guide on this page:
You might consider
undefined
to represent system-level, unexpected, or error-like absense of value andnull
to represent program-level, normal, or expected absence of value. If you need to assign one of these values to a variable or property or pass one of these values to a function,null
is almost always the right choice.
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...)
tries to get myProperty
from myObj
while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...)
returns obviously "null" because myProperty
exists, but it has the value null
assigned to it.
In order to be able to query this difference, JavaScript has null
and undefined
: While null
is - just like in other languages an object, undefined
cannot be an object because there is no instance (even not a null
instance) available.
null
is an object. Its type is null. undefined
is not an object; its type is undefined.
For example window.someWeirdProperty
is undefined, so
"window.someWeirdProperty === null"
evaluates to false while
"window.someWeirdProperty === undefined"
evaluates to true.
Moreover checkif if (!o)
is not the same as checking if (o == null)
for o
being false
.
The other fun thing about null, compared to undefined, is that it can be incremented.
x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0
This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?
In Javascript null
is not an object
type it is a primitave
type.
What is the difference? Undefined refers to a pointer that has not been set. Null refers to the null pointer for example something has manually set a variable to be of type null
Look at this:
<script>
function f(a){
alert(typeof(a));
if (a==null) alert('null');
a?alert(true):alert(false);
}
</script>
//return:
<button onclick="f()">nothing</button> //undefined null false
<button onclick="f(null)">null</button> //object null false
<button onclick="f('')">empty</button> //string false
<button onclick="f(0)">zero</button> //number false
<button onclick="f(1)">int</button> //number true
<button onclick="f('x')">str</button> //string true
From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas
But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)
Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.
That said:
var game = null; //typeof(game) is "object"
game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {};
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;
Undefined case:
var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."
- Yes, the item's value is known; it is 'defined.' It has been initialized.
- The item's value is: "there is no value."
This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."
- Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)
2.Undefined is a type itself while Null is an object.
3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.
'your programing' 카테고리의 다른 글
기존 사용자 지정 테마를 사용하여 XML에서 활동의 제목 표시 줄을 숨기는 방법 (0) | 2020.09.28 |
---|---|
Bash 스크립트에서 클립 보드로 /로부터 파이프 (0) | 2020.09.28 |
초보자를위한 Git : 확실한 실용 가이드 (0) | 2020.09.28 |
각 그룹의 마지막 레코드 검색-MySQL (0) | 2020.09.28 |
Mockito로 void 메서드를 모의하는 방법 (0) | 2020.09.28 |