!== "displicate" vs. != null 유형
정의되지 않은 파라미터 등을 체크하는 JavaScript 코드를 자주 볼 수 있습니다.
if (typeof input !== "undefined") {
// do stuff
}
장황함은 말할 것도 없고 활자 검색과 문자열 비교가 모두 수반되기 때문에 이것은 다소 낭비적인 것으로 보인다.필요하기 때문에undefined이름을 바꿀 수는 있지만요.
문입니니다다
가 이보다 더 방법은 무엇일까요?
if (null != input) {
// do stuff
}
로는, 너는 정의할 수 , 다시 정의할 수 없다.null이치노그리고, 타입 운동 때문에!=이는 두 가지 모두 합니다.undefined ★★★★★★★★★★★★★★★★★」null이 바로 기능 이는 종종 사용자가 원하는 것과 정확히 일치합니다(예: 옵션 기능 파라미터의 경우 등).
이 퍼진 것 않고 가 나쁜 을 쓴 에 대해 JSLint에게 를 지르게 할 도 있다.!=환입니니다다
왜 이게 나쁜 스타일로 여겨지죠?
typeof에서는, 식별자를 지금까지 선언한 적이 없기 때문에, 보다 안전합니다.
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
(「」의 어느 )var키워드, 함수 인수 또는 글로벌 변수로서) 가장 좋은 방법은 다음과 같습니다.
if (my_variable === undefined)
jQuery에서 할 수 있기 때문에 저는 이것으로 충분합니다:-)
않으면 '를 사용해야 .typeofReferenceError.
정의되어 있지 않은 경우는, 다음과 같이 코드를 랩 할 수 있습니다.
(function(undefined){
// undefined is now what it's supposed to be
})();
또는 를 통해 입수할 수도 있습니다.void★★★★★★★★★★★★★★★★★★:
const undefined = void 0;
// also safe
좋은 방법:
if(typeof neverDeclared == "undefined") //no errors
그러나 가장 보기 좋은 방법은 다음을 통해 확인하는 것입니다.
if(typeof neverDeclared === typeof undefined) //also no errors and no strings
정의되지 않은 이름이 변경되는 것에 대해 걱정할 필요는 없습니다.이름이 정의되지 않은 사람이 이름을 바꾸면 체크가 실패하면 몇 가지 문제보다 훨씬 더 큰 문제가 발생합니다.코드를 보호하려면 다음과 같이 IFFE(즉시 호출된 함수 표현)로 코드를 랩합니다.
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
브라우저 환경에서 글로벌 변수(이미 잘못됨)를 사용하는 경우 다음과 같이 정의되지 않았는지 확인합니다.
if(window.neverDefined === undefined) {
//Code works
}
글로벌 변수는 창 객체의 일부이므로 문자열에 캐스팅하여 문자열을 비교하는 대신 정의되지 않은 것과 대조할 수 있습니다.
게다가 변수가 정의되어 있지 않은 이유는 무엇입니까?변수가 존재하는지 확인하고 그에 따라 어떤 행동을 하는 코드를 많이 봤어요.나는 이 접근법이 어디에서 옳았는지 본 적이 없다.
정의되지 않은 재정의가 우려되는 경우 다음과 같은 도우미 방법을 사용하여 이를 방지할 수 있습니다.
function is_undefined(value) {
var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
return value === undefined_check;
}
이것은 효과가 있습니다.누군가 글을 쓸 때undefined = "foo"그는 이름만 알려준다 undefined새로운 가치를 언급하지만 그는 실제 가치를 바꾸지 않는다undefined.
void 연산자를 사용하여 정의되지 않은 값을 얻을 수도 있습니다.
if (input !== void 0) {
// do stuff
}
(다른 답변에서도 언급했듯이 변수가 선언되지 않은 경우 오류가 발생하지만 코드 검사 또는 코드 리팩터링(예: 사용)을 통해 이 경우를 배제할 수 있습니다.window.input !== void 0글로벌 변수 테스트 또는 추가에 사용됩니다.var input.)
내가 실제로 알게 된 것은(typeof input !== 'undefined')이 시나리오에서는 디폴트 함수 파라미터를 제공하기 위해 사용됩니다.
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
ES6는 다음과 같은 방법으로 기본 기능 파라미터를 도입하는 새로운 방법을 제공합니다.
function greet(name = 'Student', greeting = 'Welcome') {
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
이것은 첫 번째 옵션보다 덜 상세하고 깨끗하다.
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
console.log(greeting,name);
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
//ES6 provides new ways of introducing default function parameters this way:
function greet2(name = 'Student', greeting = 'Welcome') {
// return '${greeting} ${name}!';
console.log(greeting,name);
}
greet2(); // Welcome Student!
greet2('James'); // Welcome James!
greet2('Richard', 'Howdy'); // Howdy Richard!
(function(){
var a= b = 3;
var ed = 103;
})();
//console.log(ed); //ed is not defined
console.log("a defined? " + (typeof a !== 'undefined')); //no define
console.log("b defined? " + (typeof b !== 'undefined')); //yes define
console.log(typeof(b)); //number
console.log(typeof(4+7)); //number
console.log(b); //3
console.log(typeof("4"+"7")); //string
var e= "ggg";
console.log(typeof(e)); //string
var ty=typeof(b);
console.log(ty); //number
console.log(typeof false); //boolean
console.log(typeof 1); //number
console.log(typeof 0); //number
console.log(typeof true); //boolean
console.log(typeof Math.tan); //function
console.log(typeof function(){}); //function
if(typeof neverDeclared == "undefined") //no errors
if(typeof neverDeclared === "undefined") //no errors
//if(neverDeclared == null) //showing error
console.log(typeof {a:1}); //object
console.log(typeof null); //object
console.log(typeof JSON); //object
console.log(typeof Math); //object
console.log(typeof /a-z/); //object
console.log(typeof new Date()); //object
console.log(typeof afbc); //undefined
//console.log(typeof new);//error
document.write("<br> * oprator as math ");
var r=14*"4";
document.write(r);
document.write("<br> + oprator as string ");
var r=14+"44";
document.write(r);
document.write("<br> Minus Operator work as mathematic ");
var r=64-"44";
document.write(r);
document.write("<br>");
console.log(typeof(4*"7")); //returns number
console.log(typeof(4+"7")); //returns string
Interview Question in JavaScript
var bar = null;
console.log(typeof bar === "object"); //true yes
//because null a datatype of object
var barf = "dff";
console.log(typeof barf.constructor);//function
console.log(Array.isArray(bar));//falsss
console.log((bar !== null) && (bar.constructor === Object)); //false
console.log((bar !== null) && (typeof bar === "object")); // logs false
//because bar!==null, bar is a object
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false
console.log(typeof bar === typeof object); //false
console.log(typeof bar2 === typeof undefined); //true
console.log(typeof bar3 === typeof undefinedff); //true
console.log(typeof bar2 == typeof undefined); //true
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
if (input == undefined) { ... }
정상적으로 동작합니다.물론 아니다.null비교는 하지만, 저는 보통 이 둘을 구별할 필요가 있다면undefined그리고.null, 나는 오히려 그 둘을 구별할 필요가 있다.undefined잘못된 값만 있으면 돼요
else if (input) { ... }
할 수 있어요.
프로그램이 재정의되는 경우undefined어쨌든 뇌사상태야
제가 생각할 수 있는 유일한 이유는 IE4 호환성을 위해서였습니다.그것은,undefined키워드(안타깝게도 실제로는 키워드가 아닙니다)하지만 값은 다음과 같습니다. undefined그래서 당신은 다음과 같은 것을 가져야 합니다.
var undefined;
위의 비교는 문제없습니다.
두 번째 예에서는 보풀을 행복하게 하기 위해 이중 괄호가 필요할 수 있습니다.
언급URL : https://stackoverflow.com/questions/2703102/typeof-undefined-vs-null
'programing' 카테고리의 다른 글
| CodeIgniter 프레임워크를 사용하여 어레이에서 여러 행을 삽입하는 방법 (0) | 2023.01.17 |
|---|---|
| PHP: stdClass 개체 수 (0) | 2023.01.17 |
| 옵션이 설정된 경우 BitmapFactory.decodeStream이 null을 반환합니다. (0) | 2023.01.17 |
| Larabel - 웅변 또는 유창 랜덤 행 (0) | 2023.01.17 |
| Python에서 "raise" 키워드를 사용하는 방법 (0) | 2022.12.24 |