나는 justPrices[i].substr(commapos+2,1).
문자열은 다음과 같습니다. "blabla, 120"
이 경우 '0'이 숫자인지 확인합니다. 어떻게 할 수 있습니까?
나는 justPrices[i].substr(commapos+2,1).
문자열은 다음과 같습니다. "blabla, 120"
이 경우 '0'이 숫자인지 확인합니다. 어떻게 할 수 있습니까?
답변:
비교 연산자를 사용하여 숫자 범위에 있는지 확인할 수 있습니다.
var c = justPrices[i].substr(commapos+2,1);
if (c >= '0' && c <= '9') {
// it is a number
} else {
// it isn't
}
당신은 사용 parseInt하고 확인하는 것보다isNaN
또는 문자열에서 직접 작업하려면 다음과 같이 regexp를 사용할 수 있습니다.
function is_numeric(str){
return /^\d+$/.test(str);
}
function is_numeric_char(c) { return /\d/.test(c); }
is_numeric_char("foo1bar") == true. 숫자 문자를 확인하려면 /^\d$/.test(c)더 나은 솔루션이 될 것입니다. 어쨌든, 그것은 질문 : 아니 었
편집 : 블렌더의 업데이트 된 답변은 단일 문자 (즉 !isNaN(parseInt(c, 10)))를 확인하는 경우 여기에서 정답 입니다. 아래 내 대답은 전체 문자열을 테스트하려는 경우 좋은 솔루션입니다.
다음은 전체 문자열isNumeric 에 대해 작동하는 jQuery의 구현 (순수 JavaScript)입니다 .
function isNumeric(s) {
return !isNaN(s - parseFloat(s));
}
이 함수에 대한 주석은 다음과 같습니다.
// parseFloat NaNs numeric-cast false positives (null | true | false | "")
// ... 그러나 선행 숫자 문자열, 특히 16 진수 리터럴 ( "0x ...")을 잘못 해석합니다.
// 빼면 무한대가 NaN으로 설정됩니다.
나는 우리가이 챕스들이 이것에 대해 꽤 많은 시간을 보냈다고 믿을 수 있다고 생각합니다!
아무도 다음과 같은 솔루션을 게시하지 않은 이유가 궁금합니다.
var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);
function isDigitCode(n) {
return(n >= charCodeZero && n <= charCodeNine);
}
다음과 같은 호출로 :
if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
... // digit
} else {
... // not a digit
}
이것을 사용할 수 있습니다 :
function isDigit(n) {
return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}
여기에서는 허용되는 방법 인 http://jsperf.com/isdigittest/5 와 비교했습니다 . 나는 많은 것을 기대하지 않았기 때문에 받아 들여진 방법이 훨씬 느리다는 것을 알았을 때 꽤 놀랐습니다.
흥미로운 점은 수용된 방법이 올바른 입력 (예 : '5')이고 잘못된 경우 (예 : 'a') 느리지 만, 내 방법은 정반대 (잘못된 경우 빠르고 올바른 경우 느림)입니다.
그래도 최악의 경우 내 방법은 올바른 입력에 대해 허용 된 솔루션보다 2 배 빠르며 잘못된 입력에 대해 5 배 이상 빠릅니다.
!!([!0, !0, !0, !0, !0, !0, !0, !0, !0, !0][n]);WTF 잠재력이 크며 매우 잘 작동합니다 (에 대해 실패 007).
"length"(및 배열에있는 다른 속성)은 숫자입니다. P
이 문제를 해결하는 방법을 찾는 것이 매우 재미 있다고 생각합니다. 아래는 몇 가지입니다.
(아래의 모든 함수 는 인수가 단일 문자 라고 가정 합니다. n[0]적용 하려면 로 변경하십시오. )
function isCharDigit(n){
return !!n.trim() && n > -1;
}
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
true에 대한 " ".
charCodeAt()- 거의 4 배 더 빨랐다 - 비교 jsperf.com/isdigit3
간단한 기능
function isCharNumber(c){
return c >= '0' && c <= '9';
}
간단한 정규식을 제안합니다.
문자열의 마지막 문자 만 찾는 경우 :
/^.*?[0-9]$/.test("blabla,120"); // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120"); // true
/^.*?[0-9]$/.test(120); // true
/^.*?[0-9]$/.test(undefined); // false
/^.*?[0-9]$/.test(-1); // true
/^.*?[0-9]$/.test("-1"); // true
/^.*?[0-9]$/.test(false); // false
/^.*?[0-9]$/.test(true); // false
그리고 단일 문자를 입력으로 확인하는 경우 정규식이 더 간단합니다.
var char = "0";
/^[0-9]$/.test(char); // true
가장 짧은 해결책은 다음과 같습니다.
const isCharDigit = n => n < 10;
다음과 같이 적용 할 수도 있습니다.
const isCharDigit = n => Boolean(++n);
const isCharDigit = n => '/' < n && n < ':';
const isCharDigit = n => !!++n;
하나 이상의 chatacter를 확인하려면 다음 변형을 사용할 수 있습니다.
정규식 :
const isDigit = n => /\d+/.test(n);
비교:
const isDigit = n => +n == n;
NaN이 아닌지 확인
const isDigit = n => !isNaN(n);
isNumber = function(obj, strict) {
var strict = strict === true ? true : false;
if (strict) {
return !isNaN(obj) && obj instanceof Number ? true : false;
} else {
return !isNaN(obj - parseFloat(obj));
}
}
엄격 모드없이 출력 :
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);
true
true
false
false
엄격 모드로 출력 :
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);
true
false
false
false
당신은 이것을 시도 할 수 있습니다 (제 경우에는 작동했습니다)
문자열의 첫 번째 문자가 int인지 테스트하려면 :
if (parseInt(YOUR_STRING.slice(0, 1))) {
alert("first char is int")
} else {
alert("first char is not int")
}
char가 int인지 테스트하려면 :
if (parseInt(YOUR_CHAR)) {
alert("first char is int")
} else {
alert("first char is not int")
}
이 기능은 내가 찾을 수있는 모든 테스트 케이스에서 작동합니다. 또한 다음보다 빠릅니다.
function isNumeric (n) {
if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
return true;
}
var _n = +n;
return _n === Infinity || _n === -Infinity;
}
var isIntegerTest = /^\d+$/;
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];
function hasLeading0s(s) {
return !(typeof s !== 'string' ||
s.length < 2 ||
s[0] !== '0' ||
!isDigitArray[s[1]] ||
isIntegerTest.test(s));
}
var isWhiteSpaceTest = /\s/;
function fIsNaN(n) {
return !(n <= 0) && !(n > 0);
}
function isNumber(s) {
var t = typeof s;
if (t === 'number') {
return (s <= 0) || (s > 0);
} else if (t === 'string') {
var n = +s;
return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
} else if (t === 'object') {
return !(!(s instanceof Number) || fIsNaN(+s));
}
return false;
}
function testRunner(IsNumeric) {
var total = 0;
var passed = 0;
var failedTests = [];
function test(value, result) {
total++;
if (IsNumeric(value) === result) {
passed++;
} else {
failedTests.push({
value: value,
expected: result
});
}
}
// true
test(0, true);
test(1, true);
test(-1, true);
test(Infinity, true);
test('Infinity', true);
test(-Infinity, true);
test('-Infinity', true);
test(1.1, true);
test(-0.12e-34, true);
test(8e5, true);
test('1', true);
test('0', true);
test('-1', true);
test('1.1', true);
test('11.112', true);
test('.1', true);
test('.12e34', true);
test('-.12e34', true);
test('.12e-34', true);
test('-.12e-34', true);
test('8e5', true);
test('0x89f', true);
test('00', true);
test('01', true);
test('10', true);
test('0e1', true);
test('0e01', true);
test('.0', true);
test('0.', true);
test('.0e1', true);
test('0.e1', true);
test('0.e00', true);
test('0xf', true);
test('0Xf', true);
test(Date.now(), true);
test(new Number(0), true);
test(new Number(1e3), true);
test(new Number(0.1234), true);
test(new Number(Infinity), true);
test(new Number(-Infinity), true);
// false
test('', false);
test(' ', false);
test(false, false);
test('false', false);
test(true, false);
test('true', false);
test('99,999', false);
test('#abcdef', false);
test('1.2.3', false);
test('blah', false);
test('\t\t', false);
test('\n\r', false);
test('\r', false);
test(NaN, false);
test('NaN', false);
test(null, false);
test('null', false);
test(new Date(), false);
test({}, false);
test([], false);
test(new Int8Array(), false);
test(new Uint8Array(), false);
test(new Uint8ClampedArray(), false);
test(new Int16Array(), false);
test(new Uint16Array(), false);
test(new Int32Array(), false);
test(new Uint32Array(), false);
test(new BigInt64Array(), false);
test(new BigUint64Array(), false);
test(new Float32Array(), false);
test(new Float64Array(), false);
test('.e0', false);
test('.', false);
test('00e1', false);
test('01e1', false);
test('00.0', false);
test('01.05', false);
test('00x0', false);
test(new Number(NaN), false);
test(new Number('abc'), false);
console.log('Passed ' + passed + ' of ' + total + ' tests.');
if (failedTests.length > 0) console.log({
failedTests: failedTests
});
}
testRunner(isNumber)
위의 답변 중 하나와 유사하게
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
이 블로그 게시물 은 문자열이 Javascript | 타이프 스크립트 및 ES6
언어의 동적 유형 검사를 활용하는 간단한 솔루션 :
function isNumber (string) {
//it has whitespace
if(string === ' '.repeat(string.length)){
return false
}
return string - 0 === string * 1
}
아래 테스트 사례 참조
그냥 사용 isFinite
const number = "1";
if (isFinite(number)) {
// do something
}