JavaScript에서 null 값을 확인하려면 어떻게합니까?
JavaScript에서 null 값을 확인하려면 어떻게합니까? 아래 코드를 작성했지만 작동하지 않았습니다.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
JavaScript 프로그램에서 오류를 어떻게 찾을 수 있습니까?
자바 스크립트는 "널 (null)"값 확인과 관련하여 매우 유연합니다. 실제로 빈 문자열을 찾고 있다고 추측합니다.이 경우이 간단한 코드가 작동합니다.
if(!pass || !cpass || !email || !cemail || !user){
빈 문자열 (확인되는 ""
), null
, undefined
, false
및 숫자 0
와NaN
특별히 번호를 확인하는 경우가 미스에 대한 일반적인 실수는 것을 바랍니다 참고 0
이 방법은, 그리고 num !== 0
선호 (또는 num !== -1
또는 ~num
(해키 코드은 또한 검사에 대한 -1
)) 함수를 돌려 -1
, 예를 들어 indexOf
)
null을 구체적으로 확인하려면 다음을 사용하십시오.
if(variable === null && typeof variable === "object")
... 또는 더 간단하게 :
if(variable === null)
이 테스트는 것입니다 만 위한 통과 null
및 위해 통과하지 않을 것이다 ""
, undefined
, false
, 0
, 또는 NaN
.
나머지는 무기의 의견에 대한 답변입니다. 예, 각각 개별적으로 확인할 수 있습니다.
의 사용을 구현 absolutely equals: ===
하고 typeof
수표를 반드시 확인해야합니다.
JSFiddle을 여기에서 만들어 모든 개별 테스트가 작동하는지 보여줍니다.
테스트 결과는 다음과 같습니다.
Null Test:
if(variable === null && typeof variable === "object")
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if(variable === "" && typeof variable === "string")
- variable = ""; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if(variable === undefined && typeof variable === "undefined")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if(variable === false && typeof variable === "boolean")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if(variable === 0 && typeof variable === "number")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if(!parseFloat(variable) && variable != 0 && typeof variable === "number")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
보시다시피, 테스트하기가 조금 더 어렵습니다 NaN
.
바로 교체 ==
와 ===
모든 장소에서 가능합니다.
==
느슨하거나 추상적 인 평등 비교
===
엄격한 평등 비교입니다
자세한 내용은 평등 비교 및 동일성에 대한 MDN 기사를 참조하십시오 .
엄격한 평등 연산자 :-
우리는 null을 확인할 수 있습니다 ===
if ( value === null ){
}
사용하여 if
if( value ) {
}
값이 아닌 경우 true로 평가됩니다 .
- 없는
- 찾으시는 주소가 없습니다
- NaN
- 빈 문자열 ( "")
- 그릇된
- 0
null
구문 을 명시 적으로 확인 하지만 간단한 구문 으로 허용되는 답변보다 개선되었습니다 .
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
}
// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
console.log ("Yayy! None of them are null");
} else {
console.log ("Oops! At-lease one of them is null");
}
먼저 함수 본문이없는 return 문이 있습니다. 오류가 발생할 가능성이 있습니다.
보다 확실한 확인 방법은 간단히! 운영자:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
마지막으로 try catch를 사용할 수 있습니다
try {
document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
} catch (e) {
if (e.name.toString() == "TypeError") //evals to true in this case
//do something
} finally {}
당신은 또한 throw
당신의 자신의 오류 를 할 수 있습니다 . 참조 이 .
JavaScript에서는 문자열이 없습니다 null
.
느슨한 항등 연산자가 특정 유형의 강제 변환을 수행 한다는 것을 알고 있기 때문에 빈 문자열 인 pass == null
경우 true 를 기대할 수 있습니다 .pass
==
예를 들어이 표현식은 다음과 같습니다.
'' == 0
대조적으로, 완전 평등 연산자 ===
는 이것이 거짓이라고 말합니다 :
'' === 0
점을 감안 ''
하고 0
느슨하게 동일, 당신은 수있는 합리적으로 추측 그 ''
와 null
느슨하게 같다. 그러나 그렇지 않습니다.
이 표현은 거짓이다 :
'' == null
문자열을 비교 한 결과 null
는 false입니다. 따라서 pass == null
다른 모든 테스트는 항상 거짓이며 사용자에게 경고가 표시되지 않습니다.
코드를 수정하려면 각 값을 빈 문자열과 비교하십시오.
pass === ''
그것이 pass
문자열인지 확실하다면 pass == ''
, 빈 문자열만이 빈 문자열과 느슨하기 때문에 작동합니다. 반면에 일부 전문가는 느슨한 항등 연산자가 수행하는 유형 강제 변환을 구체적으로 수행하지 않으려는 경우 항상 JavaScript에서 엄격한 동등성을 사용하는 것이 좋습니다.
어떤 값 쌍이 느슨하게 동일한 지 알고 싶다면 이 주제 에 대한 Mozilla 기사 의 "동일한 비교"표를 참조하십시오 .
자바 스크립트에서 undefined 및 null 을 확인 하려면 다음을 작성해야합니다.
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
이것은 NaN 확인과 관련하여 WebWanderer의 솔루션에 대한 의견입니다 (아직 공식적인 의견을 남길 충분한 담당자가 없습니다). 솔루션은 다음과 같이 읽습니다.
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
그러나 이것은 반올림 것 유리수 실패 할 것 0
같은, variable = 0.1
. 더 나은 테스트는 다음과 같습니다.
if(isNaN(variable) && typeof variable === "number")
실제로 if (value !== null || value !== undefined)
사용 if (value)
하면 0 또는 false 값을 필터링 할 수 있기 때문에 사용해야 할 수도 있습니다.
다음 두 가지 기능을 고려하십시오.
const firstTest = value => {
if (value) {
console.log('passed');
} else {
console.log('failed');
}
}
const secondTest = value => {
if (value !== null && value !== undefined) {
console.log('passed');
} else {
console.log('failed');
}
}
firstTest(0); // result: failed
secondTest(0); // result: passed
firstTest(false); // result: failed
secondTest(false); // result: passed
firstTest(''); // result: failed
secondTest(''); // result: passed
firstTest(null); // result: failed
secondTest(null); // result: failed
firstTest(undefined); // result: failed
secondTest(undefined); // result: failed
내 상황에서, 난 그냥 값이 null이 있는지 확인하기 위해 필요하고 정의되지 않은 난 필터에 싶지 않았다 0
거나 false
또는 ''
값. 따라서 두 번째 테스트를 사용했지만 필터도 필터링해야 할 수 있으므로 첫 번째 테스트를 사용하게 될 수 있습니다.
값이 null인지 테스트하는 다른 방법을 찾았습니다.
if(variable >= 0 && typeof variable === "object")
null
A와 작용 number
과 object
동시에. 비교 null >= 0
또는 null <= 0
결과 true
. 비교 null === 0
하거나 null > 0
또는 것은 null < 0
거짓 발생합니다. 그러나 null
객체와 마찬가지로 null로 감지 할 수 있습니다.
나는 더 복잡한 함수를 만든 natureof 마녀 대해서 typeof보다 더 잘 할 것입니다 포함하거나 그룹화 계속 어떤 종류의 이야기 될 수있다
/* function natureof(variable, [included types])
included types are
null - null will result in "undefined" or if included, will result in "null"
NaN - NaN will result in "undefined" or if included, will result in "NaN"
-infinity - will separate negative -Inifity from "Infinity"
number - will split number into "int" or "double"
array - will separate "array" from "object"
empty - empty "string" will result in "empty" or
empty=undefined - empty "string" will result in "undefined"
*/
function natureof(v, ...types){
/*null*/ if(v === null) return types.includes('null') ? "null" : "undefined";
/*NaN*/ if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" :
/*-infinity*/ (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" :
/*number*/ (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
/*array*/ if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
/*empty*/ if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" :
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
else return typeof v
}
// DEMO
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]
for(i in types){
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined"))
}
lodash 모듈을 사용하여 값이 null인지 정의되지 않았는지 확인할 수 있습니다.
_.isNil(value)
Example
country= "Abc"
_.isNil(country)
//false
state= null
_.isNil(state)
//true
city= undefined
_.isNil(state)
//true
pin= true
_.isNil(pin)
// false
참조 링크 : https://lodash.com/docs/#isNil
예를 들어 DB에서 부울 값이 오는 경우에는 작동하지 않습니다.
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
공감하기 전에주의 깊게보십시오.
변수가 선언 되었지만 값이 지정되지 않은 경우 JAVASCRIPT의 AFAIK 는 유형입니다 . value 대신에 인스턴스 를 보유하고 있더라도 변수를 확인할 수 있습니다 .undefined
object
null을 검사 true
하여 API에서 반환되는 nullity를 확인하는 도우미 메서드를 만듭니다 .
변수가 비어 있는지 확인하는 도우미 함수 :
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch 예외적 API 호출 :
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
일부 테스트 사례 :
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));
나는 놀라운 일을하는 매우 간단한 기능을 만들었습니다.
function safeOrZero(route) {
try {
Function(`return (${route})`)();
} catch (error) {
return 0;
}
return Function(`return (${route})`)();
}
경로는 폭파 할 수있는 모든 값의 체인입니다. jQuery / cheerio 및 객체 등에 사용합니다.
예 1 : this와 같은 간단한 객체 const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};
.
그러나 우리가 만들지 않은 매우 큰 물체 일 수 있습니다. 그래서 나는 그것을 통과합니다.
let value1 = testobj.items[2].val; // "hum!"
let value2 = testobj.items[3].val; // Uncaught TypeError: Cannot read property 'val' of undefined
let svalue1 = safeOrZero(`testobj.items[2].val`) // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`) // 0
물론 당신이 선호한다면 당신은 ... null
또는 'No value'
당신의 필요에 맞는 것을 사용할 수 있습니다 .
일반적으로 DOM 쿼리 또는 jQuery 선택기가 없으면 오류가 발생할 수 있습니다. 그러나 다음과 같은 것을 사용하십시오 :
const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
[...]
}
이 시도:
if (!variable && typeof variable === "object") {
// variable is null
}
참고 URL : https://stackoverflow.com/questions/6003884/how-do-i-check-for-null-values-in-javascript
'Programming' 카테고리의 다른 글
Codesign 오류 : 만료 된 프로파일을 삭제 한 후 프로비저닝 프로파일을 찾을 수 없습니다 (0) | 2020.02.12 |
---|---|
Android에서 소프트웨어 키보드의 가시성을 확인하는 방법은 무엇입니까? (0) | 2020.02.12 |
하나의 로그 회전 검사를 수동으로 실행할 수 있습니까? (0) | 2020.02.12 |
==와 같음 ()의 C # 차이 (0) | 2020.02.11 |
Swift 언어에서 느낌표는 무엇을 의미합니까? (0) | 2020.02.11 |