programing

JavaScript에서 번호가 NaN인지 확인하려면 어떻게 해야 합니까?

javaba 2022. 10. 6. 21:17
반응형

JavaScript에서 번호가 NaN인지 확인하려면 어떻게 해야 합니까?

Firefox의 JavaScript 콘솔에서만 시도했지만 다음 문장은 모두 true로 반환되지 않습니다.

parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;

다음 코드를 사용해 보십시오.

isNaN(parseFloat("geoff"))

값이 숫자뿐만 아니라 NaN인지 여부를 확인하려면 다음을 참조하십시오.Javascript에서 NaN 테스트는 어떻게 하나요?

이 기술은 매우 간단한 "Effective JavaScript"라는 책에서 우연히 알게 되었습니다.

NaN은 JavaScript 값 자체와 동등하지 않은 것으로 간주되는 유일한 값이기 때문에 값이 NaN인지 여부는 항상 테스트할 수 있습니다.

var a = NaN;
a !== a; // true 

var b = "foo";
b !== b; // false 

var c = undefined; 
c !== c; // false

var d = {};
d !== d; // false

var e = { valueOf: "foo" }; 
e !== e; // false

@allsyed가 코멘트할 때까지 이 사실을 몰랐습니다만, 이것은 ECMA 사양에 기재되어 있습니다.https://tc39.github.io/ecma262/ # sec - isnan - number

다음 코드 사용:

isNaN('geoff');

MDN 관련 문서를 참조하십시오.

alert ( isNaN('abcd'));  // alerts true
alert ( isNaN('2.0'));  // alerts false
alert ( isNaN(2.0));  // alerts false

type Number의 값에 대해서는 type Number의 값이 type Number와 type Number가 일치하는지 여부를 테스트합니다.NaN 함수 " " " " " " " " "isNaN

isNaN(any-Number);

JS의 모든 유형에 적용되는 일반적인 접근방식의 경우 다음 중 하나를 사용할 수 있습니다.

ECMAScript-5 사용자의 경우:

#1
if(x !== x) {
    console.info('x is NaN.');
}
else {
    console.info('x is NOT a NaN.');
}

ECMAScript-6을 사용하는 사용자의 경우:

#2
Number.isNaN(x);

또한 ECMAScript 5와 6 모두에서 일관성을 유지하기 위해 이 폴리필을 Number.isNan에 사용할 수도 있습니다.

#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
    return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

자세한 내용은 이 답변에서 확인하십시오.

ES6에서는Object.is(..)는 2가지 할 수 입니다.

var a = 3 / 'bar';
Object.is(a, NaN); // true

하셔야 합니다.isNaN(value)수수: :

  • 크로스 브라우저 지원
  • 매뉴얼에 대해서는 isNaN을 참조해 주십시오.

예:

 isNaN('geoff'); // true
 isNaN('3'); // false

이것이 당신에게 도움이 되길 바랍니다.

NaN은 그런 식으로 테스트할 수 없는 특별한 값입니다.재밌는 건 제가 공유하고 싶은 건

var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
    alert('nanValue is NaN');

이것은 NaN 값에 대해서만 true를 반환하며 안전한 테스트 방법입니다.동일한 변수가 서로 동일하지 않은지 테스트하는 것은 분명 의미가 없기 때문에 함수로 감싸거나 최소한 주석이라도 달아야 합니다.

JavaScript에서 NaN은 "Not A Number"를 의미하지만, 실제로는 그 유형이 숫자입니다.

typeof(NaN) // "number"

변수가 값 NaN인지 여부를 확인하려면 단순히 함수 isNaN()을 사용할 수 없습니다.isNaN()에는 다음과 같은 문제가 있기 때문입니다.

var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN

여기서 실제로 발생하는 것은 myVar가 암묵적으로 숫자에 강제된다는 것입니다.

var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact

A는 숫자가 아니기 때문에 말이 되는군요.그러나 myVar가 NaN에 정확히 적합한지 확인해야 합니다.

따라서 isNaN()은 도움이 되지 않습니다.그럼 어떻게 할까요?

NaN이 JavaScript 값 자체와 동등하지 않은 것으로 간주되기 때문에 NaN이 유일한 JavaScript 값이라는 점을 고려하여 NaN이 자체와 동등함을 확인할 수 있습니다!==

var myVar; // undefined
myVar !== myVar // false

var myVar = "A";
myVar !== myVar // false

var myVar = NaN
myVar !== myVar // true

결론적으로!== 변수 자체가 참이라면 이 변수는 정확히 NaN 값입니다.

function isOfValueNaN(v) {
    return v !== v;
}

var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false

「 」의 하려면 , 「 」를 .'1.2geoff'이 되면 '파싱'을 쓰면 돼요.Number()대신 파서를 사용합니다.

그래서 이것보다는:

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

다음을 수행합니다.

Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true

편집: 여기서 또 다른 문제가 발견되었습니다만... 값이 "false"에 전달됨("false" true")"Number()0 합니다.parse Float 은번flo 。을 하다

function definitelyNaN (val) {
    return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}

그리고 그것은 겉으로 보기에 모든 것을 커버합니다.Lodash에 비해 90% 했습니다._.isNaNNaN을 사용하다

http://jsperf.com/own-isnan-vs-underscore-lodash-isnan

확실히 하기 위해서, 제 것은 「번호가 아니다」라고 하는 것에 대한 인간의 문자 그대로의 해석과 「NaN」이라고 하는 것을 확인하는 컴퓨터 문자 그대로의 해석을 담당합니다.

@chiborg의 답변은 맞지만 주의할 점은 다음과 같습니다.

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

요점은 입력 검증에 이 방법을 사용하면 결과가 상당히 자유로워진다는 것입니다.

네, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.parseFloat(string))parseInt(string, radix)에 '를 붙여서 '를 붙입니다.isNaN(), 숫자와 얽혀 있는 해 주세요.

규칙은 다음과 같습니다.

NaN != NaN

isNaN() 함수의 문제는 다음과 같은 경우에 예기치 않은 결과를 반환할 수 있다는 것입니다.

isNaN('Hello')      //true
isNaN('2005/12/12') //true
isNaN(undefined)    //true
isNaN('NaN')        //true
isNaN(NaN)          //true
isNaN(0 / 0)        //true

값이 실제로 NaN인지 여부를 확인하는 더 좋은 방법은 다음과 같습니다.

function is_nan(value) {
    return value != value
}

is_nan(parseFloat("geoff"))

사용 환경에서 ECMAScript 2015를 지원하는 경우 를 사용하여 실제 을 확인할 수 있습니다.NaN.

의 문제는 수치 이외의 데이터와 함께 사용할 경우 MDN에 따라 혼동되는 규칙이 거의 적용되지 않는다는 것입니다.예를들면,

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({});        // true

따라서 ECMA Script 2015 지원 환경에서는

Number.isNaN(parseFloat('geoff'))

심플한 솔루션!

정말 심플해!자! 이 방법을 써라!

function isReallyNaN(a) { return a !== a; };

다음과 같이 간단하게 사용:

if (!isReallyNaN(value)) { return doingStuff; }

기능을 사용한 퍼포먼스 테스트와

또한: 몇 가지 대체 구현에 대해서는 아래의 첫 번째 예를 참조하십시오.


예:

function isReallyNaN(a) { return a !== a; };

var example = {
    'NaN': NaN,
    'an empty Objet': {},
    'a parse to NaN': parseFloat('$5.32'),
    'a non-empty Objet': { a: 1, b: 2 },
    'an empty Array': [],
    'a semi-passed parse': parseInt('5a5'),
    'a non-empty Array': [ 'a', 'b', 'c' ],
    'Math to NaN': Math.log(-1),
    'an undefined object': undefined
  }

for (x in example) {
    var answer = isReallyNaN(example[x]),
        strAnswer = answer.toString();
    $("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
        html: x
    }), $("<td />", {
        html: strAnswer
    })))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>

대체 이름을 가진 방법을 사용하지 않고 보다 글로벌하게 사용할 수 있도록 하려면 구현을 위해 몇 가지 대체 경로를 사용할 수 있습니다.경고 이러한 솔루션에는 네이티브 오브젝트의 변경이 포함되어 있어 최적의 솔루션이 아닐 수 있습니다.사용할 수 있는 다른 라이브러리는 네이티브 코드 또는 유사한 변경 사항에 따라 달라질 수 있으므로 항상 주의하십시오.

1: Native (네이티브) 1: " " "isNaN★★★★★★ 。

//  Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }

2: Number 」 : 2 : 「 」
5~*ECMA 5~6용

Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
//  Use as simple as
Number.isNaN(NaN)

대체 솔루션

간단한 창 방법 객체가 비어있는 경우 테스트를 작성했습니다.'정확한' NaN이라면 주지 않는 것은 조금 다르지만, 빈 아이템을 찾을 때도 도움이 될 수 있기 때문에 토하고 싶다고 생각했습니다.

/** isEmpty(varried)
 *  Simple method for testing if item is "empty"
 **/
;(function() {
   function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
   window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();

예:

;(function() {
   function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
   window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();

var example = {
    'NaN': NaN,
    'an empty Objet': {},
    'a parse to NaN': parseFloat('$5.32'),
    'a non-empty Objet': { a: 1, b: 2 },
    'an empty Array': new Array(),
    'an empty Array w/ 9 len': new Array(9),
    'a semi-passed parse': parseInt('5a5'),
    'a non-empty Array': [ 'a', 'b', 'c' ],
    'Math to NaN': Math.log(-1),
    'an undefined object': undefined
  }

for (x in example) {
	var answer = empty(example[x]),
		strAnswer = answer.toString();
	$("#t1").append(
		$("<tr />", { "class": strAnswer }).append(
			$("<th />", { html: x }),
			$("<td />", { html: strAnswer.toUpperCase() })
		)
	)
};


function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>


빈 상태일 경우 매우 상세하게 확인

이 마지막 항목은 객체가 빈 객체로 가득 차 있는지 확인하는 경우에도 약간 깊이가 있습니다.개선의 여지가 있고 가능한 구덩이가 있다고 확신하지만, 지금까지는 모든 것을 잡을 수 있을 것 같습니다.

function isEmpty(a) {
	if (!a || 0 >= a) return !0;
	if ("object" == typeof a) {
		var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
		if ( /^$|\{\}|\[\]/.test(b) ) return !0;
		else if (a instanceof Array)  {
			b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
			if ( /^$|\{\}|\[\]/.test(b) ) return !0;
		}
	}
	return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);

var example = {
    'NaN': NaN,
    'an empty Objet': {},
    'a parse to NaN': parseFloat('$5.32'),
    'a non-empty Objet': { a: 1, b: 2 },
    'an empty Array': new Array(),
    'an empty Array w/ 9 len': new Array(9),
    'a semi-passed parse': parseInt('5a5'),
    'a non-empty Array': [ 'a', 'b', 'c' ],
    'Math to NaN': Math.log(-1),
    'an undefined object': undefined,
    'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
    'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
  }

for (x in example) {
	var answer = empty(example[x]),
		strAnswer = answer.toString();
	$("#t1").append(
		$("<tr />", { "class": strAnswer }).append(
			$("<th />", { html: x }),
			$("<td />", { html: strAnswer.toUpperCase() })
		)
	)
};


function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>

function isNotANumber(n) {
  if (typeof n !== 'number') {
    return true;
  } 
  return n !== n;
}

JavaScript에서는 다음과 같은 이유로 언더스코어 함수를 사용합니다.

isNaN(undefined) 
-> true

적어도 그 정도는 알아둬야죠

또 다른 대안을 제시하겠습니다.이것이 반드시 여기 있는 다른 제품보다 좋은 것은 아니지만, 검토할 가치가 있다고 생각합니다.

function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }

에 있는 는 을 제외한 모든 가 그렇다는 이다.0 ★★★★★★★★★★★★★★★★★」NaNtrue.

, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★Number.isNaN 가 좋다.isNan

결과

customIsNaN(NaN);            // true
customIsNaN(0/0);            // true
customIsNaN(+new Date('?')); // true

customIsNaN(0);          // false
customIsNaN(false);      // false
customIsNaN(null);       // false
customIsNaN(undefined);  // false
customIsNaN({});         // false
customIsNaN('');         // false

것을 때 이 될 수 .isNaN★★★★★★ 。

이것도 생각할 수 있습니다.

function isNaNCustom(value){
    return value.toString() === 'NaN' && 
           typeof value !== 'string' && 
           typeof value === 'number'
}

「Node.js」는 「NaN()」입니다.
나는 그 일을 함께 했다.

var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
NaN === NaN;        // false
Number.NaN === NaN; // false
isNaN(NaN);         // true
isNaN(Number.NaN);  // true

동등 연산자(== 및 ===)는 NaN에 대한 값을 검정하는 데 사용할 수 없습니다.

Mozilla 문서 보기 글로벌 NaN 속성은 Not-A-Numbe나타내는 값입니다.

가장 좋은 방법은 buit-in 함수인 isNaN()을 사용하여 NaN을 확인하는 것입니다.모든 브라우저가 이 방법을 지원합니다.

IEEE 754에 따르면, NaN과 관련된 모든 관계는 !=를 제외한 거짓으로 평가된다.예를 들어 A 또는 B 또는 둘 다 NaN이면 (A > = B) = false, (A < = B) = false가 된다.

답변은 StackOverflow 상의 다른 질문에 대해 작성했습니다.이 질문에서는 다른 사람이 언제 체크하는지 확인합니다.NaN == null중복으로 표시되어 있어서 일을 낭비하고 싶지 않아요.

Mozilla Developer Network 보기:NaN.


단답

그냥 사용하다distance || 0값이 적절한 수치인지 확인하고 싶을 때 또는isNaN()확인하러 왔습니다.

장답

NaN(Not-a-Number)은 javascript의 이상한 전역 개체로, 일부 수학적 연산이 실패했을 때 자주 반환됩니다.

당신이 확인하길 원했군요NaN == null결과적으로false. 짝수NaN == NaN로부터의 결과.false.

A 변수가 다음과 같은지 여부를 확인하는 간단한 방법NaN글로벌 함수입니다.isNaN().

또 하나는x !== xx가 NaN일 때만 해당됩니다(@raffael-schweikert에게 상기시켜 주셔서 감사합니다).

하지만 왜 짧은 대답이 먹혔을까요?

알아보자.

전화할 때NaN == false결과는false, 와 같은NaN == true.

사양의 어딘가에 JavaScript에는 다음과 같은 false 값이 항상 포함된 레코드가 있습니다.

  • NaN- 번호 외
  • ""- 빈 문자열
  • false false(부울값 false).
  • null- object(예: null object).
  • undefined 변수 - 정의되지 않은 변수
  • 0(+0 및 '0' 포함

MDN의 parse Float 페이지에 다른 솔루션이 기재되어 있습니다.

필터 기능을 제공하여 엄밀한 해석을 실시합니다.

var filterFloat = function (value) {
    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
      .test(value))
      return Number(value);
  return NaN;
}


console.log(filterFloat('421'));               // 421
console.log(filterFloat('-421'));              // -421
console.log(filterFloat('+421'));              // 421
console.log(filterFloat('Infinity'));          // Infinity
console.log(filterFloat('1.61803398875'));     // 1.61803398875
console.log(filterFloat('421e+0'));            // NaN
console.log(filterFloat('421hop'));            // NaN
console.log(filterFloat('hop1.61803398875'));  // NaN

에 '먹다'를 쓰면 .isNaNNaN

재미로 다른 방법을 찾았지

function IsActuallyNaN(obj) {
  return [obj].includes(NaN);  
}

정확한 확인 방법은 다음과 같습니다.

//takes care of boolen, undefined and empty

isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'

마법처럼 작동하는 작은 기능을 만들었습니다.직감적으로 보이는 NaN을 확인하는 대신 번호를 확인합니다.이런 식으로 하는 게 처음은 아니지만, 공유하려고 했어요.

function isNum(val){
    var absVal = Math.abs(val);
    var retval = false;
    if((absVal-absVal) == 0){
        retval = true
    }

    return retval;
}

하지만 marksyzm에 대해서는 .Infinity인피니티는 기술적으로 숫자가 아니기 때문입니다.

제가 생각해낸 건isNumber이치노

function isNumber(i) {
    return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}

console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));

업데이트: 이 코드는 일부 파라미터에서 오류가 발생하므로 개선했습니다.

function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
	} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
	} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
	} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
	} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
	} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
	} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
	}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));

alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);

이것은 우아하지 않습니다만, isNAN()을 사용해 본 결과, 또 다른 대체 솔루션인 이 솔루션에 도달했습니다.이 예에서는 플로트를 마스킹하고 있기 때문에 '.'도 사용할 수 있습니다.또한 이 값을 반대로 하여 숫자가 사용되지 않도록 할 수도 있습니다.

("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)

이것은 단일 문자 평가이지만 문자열을 루프하여 숫자를 확인할 수도 있습니다.

Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
    
Number('12345').toString() === 'NaN' // false  

// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0

// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1

조건부로 둘 다 시험해 보다

if(isNaN(parseFloat('geoff'))  && typeof(parseFloat('geoff')) === "number");
//true

결과를 String으로 변환하여 'NaN'과 비교하기만 하면 됩니다.

var val = Number("test");
if(String(val) === 'NaN') {
   console.log("true");
}

언급URL : https://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript

반응형