programing

JavaScript에서 null 값을 확인하려면 어떻게 해야 합니까?

minecode 2023. 1. 14. 09:46
반응형

JavaScript에서 null 값을 확인하려면 어떻게 해야 합니까?

JavaScript에서 null 값을 확인하려면 어떻게 해야 합니까?아래에 코드를 썼는데 작동하지 않았어요.

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

그리고 JavaScript 프로그램에서 오류를 찾으려면 어떻게 해야 하나요?

JavaScript는 "null" 값을 확인하는 데 매우 유연합니다.실제로는 빈 문자열을 찾고 있는 것 같습니다.이 경우 다음과 같은 간단한 코드가 작동합니다.

if(!pass || !cpass || !email || !cemail || !user){

빈 이 체크됩니다( 자문 ( ( (( which( which 。""null,undefined,false 숫자 '''''''는0 ★★★★★★★★★★★★★★★★★」NaN.

특정 번호를 확인하는 경우, 놓치는 것은 흔한 실수입니다.0 「」, 「」, 「」를 사용합니다.num !== 0 '')num !== -1 ★★★★★★★★★★★★★★★★★」~num )-1)를 지정합니다.-1 예 , ) 。indexOf를 참조해 주세요.

null을 특정하게 확인하려면 다음을 사용합니다.

if (variable === null)

테스트는 다음 기간에만 합격합니다.null 않을 것이다."",undefined,false,0 , 「」NaN.

같은거짓 같은' 에 대해 값에!variable를 참조해 주세요.

체크의 일부에 는, 「사용할 수 없다」, 「사용할 수 없다」의 absolutely equals: === ★★★★★★★★★★★★★★★★★」typeof.

여기 JSFiddle을 만들어 모든 개별 테스트가 작동하는 것을 보여드렸습니다.

각 체크의 출력은 다음과 같습니다.

Null Test:

if (variable === null)

- 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 === '')

- 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 (typeof variable == "undefined")

-- or --

if (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)

- 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)

- 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 (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)

-- or --

if (isNaN(variable))

- 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인지 확인할 수 있습니다.

[pass,cpass,email,cemail,user].some(x=> x===null) 

let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;

if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {     
    alert("fill all columns");
    //return false;  
}   

:왜 너:: bonus bonus=== ==(소스)

a == b

여기에 이미지 설명을 입력하십시오.

a === b

여기에 이미지 설명을 입력하십시오.

완전 등식 연산자:-

하려면 'null'을 'null을 사용하세요.===

if ( value === null ){

}

★★★★★★★★★★★★★★를 사용하는 것만으로if

if( value ) {

}

값이 다음 값이 아닌 경우 true로 평가됩니다.

  • 무효
  • 정의되어 있지 않다
  • NaN
  • 빈 문자열("")
  • 거짓의
  • 0

언뜻 보기에는 커버리지와 엄격성 사이의 단순한 트레이드오프처럼 보입니다.

  • ==는, 복수의 값을 커버해, 보다 적은 코드로 보다 많은 시나리오를 처리할 수 있습니다.
  • ===가장 엄격하기 때문에 예상할 수 있습니다.

이기기 「」가 되는 .===만능의 해결책

여기에 이미지 설명 입력

하지만 그것은 틀렸다.그럼에도 불구하고.===는 예측할 수 있습니다.시나리오를 간과하기 때문에 항상 예측 가능한 코드가 되는 것은 아닙니다.

const options = { };
if (options.callback !== null) {
  options.callback();      // error --> callback is undefined.
}

==는 늘체크에 보다 합니다.예측할 수 없습니다.

  • 으로는, 「 」입니다.null ★★★★★★★★★★★★★★★★★」undefined둘 다 같은 의미입니다. "뭔가 누락되었습니다."예측 가능성을 위해 두 값을 모두 선택해야 합니다.그리고 나서.== null이 두 가지 값을 정확하게 커버하기 때문에 완벽하게 동작합니다.(즉,상당합니다).

  • 예외적인 경우, 두 가지를 명확하게 구별해야 합니다.null ★★★★★★★★★★★★★★★★★」undefined하게 하는 === undefined ★★★★★★★★★★★★★★★★★」=== null. (예: 누락/삭제/삭제비어 있음/삭제/제거의 구별)하지만 드문 일이다.

그것은 드물 뿐만 아니라 피해야 할 것이다.수 .undefined기존 데이터베이스에 있습니다.undefined상호 운용성 때문에 API 설계 값도 사용할 수 없습니다.하지만 전혀 구별하지 않더라도, 그런 일이 일어나지 않을 거라고 추측할 수는 없습니다.우리 주변 사람들은 간접적으로 일반화하는 행동을 취한다.null/undefined(이 때문에, 이러한 질문은 「고유」로서 닫힙니다).

이치노 사용해도 것이 없습니다.== null을 사용하다

// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null && 
    options.callback !== undefined) {
  options.callback();
}


// FIX 2 --> but == covers both
const options = { };
if (options.callback != null) {
  options.callback();
}

// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();

으로써 인정된 답변보다 개선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");
}

첫째, 함수 본문이 없는 반환문이 있습니다.그것은 아마 오류를 일으킬 것이다.

보다 깔끔한 체크 방법은 ! 연산자를 사용하는 것입니다.

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}

드디어 트라이캐치를 사용할 수 있습니다.

 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일 때 맞다pass는 느슨한 연산자 빈을 알고 있기 에 빈 입니다. 느슨한 평등==특정 유형의 강압을 행사합니다.

예를 들어, 다음 표현은 참입니다.

'' == 0

등호 '''는 '''로, '''는 '''로'''''는 '''로'''는 '''로,===

'' === 0

'' ★★★★★★★★★★★★★★★★★」0대등하다, 라고할 수 있습니다.'' ★★★★★★★★★★★★★★★★★」null느슨하게 동등하다.지만,,,그그그다않않않않않않

이 식은 false입니다.

'' == null

을 ""와 null 때문에,은,pass == null다른 모든 테스트는 항상 false이며 사용자는 경고를 받지 않습니다.

코드를 수정하려면 각 값을 빈 문자열과 비교합니다.

pass === ''

passpass == ''빈 문자열만 빈 문자열과 느슨하게 같기 때문에도 동작합니다.한편, 일부 전문가들은 느슨한 평등 연산자가 수행하는 유형 강압을 특별히 원하지 않는 한 JavaScript에서 항상 엄격한 평등을 사용하는 것이 좋은 관행이라고 말합니다.

값 쌍이 느슨하게 동일한지 확인하려면 이 항목에 대한 Mozilla 문서의 "동일성 비교" 표를 참조하십시오.

javascript에서 정의되지 않은 과 null을 확인하려면 다음 내용을 작성하기만 하면 됩니다.

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}

는 실, 각, 각, 각, 각, 제, 제, actually, actually, actually, actually, actually, actually,if (value !== null && value !== undefined) '아예'를 if (value)값을 도 있습니다.

다음 두 가지 기능을 고려합니다.

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

되어 있지 되고, 필터링을 하고 .0 ★★★★★★★★★★★★★★★★★」false ★★★★★★★★★★★★★★★★★」''. 해서 첫 번째 를 사용할.그래서 두 번째 테스트를 사용했는데, 필터도 필요해서 첫 번째 테스트를 사용할 수 있습니다.

NaN 체크에 관한 WebWander의 솔루션에 대한 코멘트입니다(아직 정식 코멘트를 남길 정도의 레퍼토리가 없습니다).솔루션은 다음과 같습니다.

if(!parseInt(variable) && variable != 0 && typeof variable === "number")

는 실패한다.0 「」, 「」등입니다.variable = 0.1는 다음과

if(isNaN(variable) && typeof variable === "number")

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

변수선언되었지만 값이 할당되지 않은 경우 JAVASCRIBT에서 AFAIK의 유형은 다음과 같습니다.undefined할 수 object가치 대신 몇 가지 인스턴스를 보유할 수 있습니다.

하기 위한 을 반환한다.trueAPI를 사용합니다.

변수가 비어 있는지 확인하는 도우미 기능:

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));

값이 null인지 여부를 테스트하는 다른 방법을 찾았습니다.

if(variable >= 0 && typeof variable === "object")

null을 하다number ★★★★★★★★★★★★★★★★★」object★★★★★★★의 비교null >= 0 ★★★★★★★★★★★★★★★★★」null <= 0이 되다true.비교하는null === 0 ★★★★★★★★★★★★★★★★★」null > 0 ★★★★★★★★★★★★★★★★★」null < 0잘못된 결과를 초래합니다. 지.........null할 수 있습니다.

나는 마녀의 본성이 유형보다 더 잘 될 것이고 어떤 유형을 포함할지 또는 그룹화 시킬 수 있는 보다 복잡한 기능을 만들었다.

/* 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")) 
}

매우 심플한 기능을 만들어 경이롭게 동작합니다.

function safeOrZero(route) {
  try {
    Function(`return (${route})`)();
  } catch (error) {
    return 0;
  }
  return Function(`return (${route})`)();
}

루트는 폭발할 수 있는 값의 사슬입니다.jQuery/cheerio나 오브젝트 등에 사용합니다.

1:과 같은 11: 음음음 such such such such such such such such such such such such suchconst 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){
  [...]
}

오퍼레이터와의 옵션 체크는 어떻습니까?

예를 들어 다음과 같습니다.

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}

이것을 시험해 보세요.

if (!variable && typeof variable === "object") {
    // variable is null
}

다음 예에 대해 DB에서 부울 값이 수신되는 경우에는 이 기능이 작동하지 않습니다.

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }

오류 상태를 확인하는 중:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}

빈 값에 대한 간단한 솔루션:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }

언급URL : https://stackoverflow.com/questions/6003884/how-do-i-check-for-null-values-in-javascript

반응형