ฉันต้องการตรวจสอบว่า 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)จะเป็นทางออกที่ดีกว่า แต่อย่างไรก็ตามมันไม่ใช่คำถาม :)
แก้ไข: คำตอบที่อัปเดตของ Blender เป็นคำตอบที่ถูกต้องที่นี่หากคุณกำลังตรวจสอบอักขระเดี่ยว (กล่าวคือ !isNaN(parseInt(c, 10)) ) คำตอบของฉันด้านล่างเป็นวิธีแก้ปัญหาที่ดีหากคุณต้องการทดสอบสตริงทั้งหมด
นี่คือisNumericการนำไปใช้งานของ jQuery (ใน JavaScript บริสุทธิ์) ซึ่งทำงานกับสตริงทั้งหมด :
function isNumeric(s) {
return !isNaN(s - parseFloat(s));
}
ความคิดเห็นสำหรับฟังก์ชันนี้อ่านว่า:
// parseFloat NaNs ตัวเลขที่สร้างผลบวกเท็จ (null | true | false | "")
// ... แต่ตีความสตริงเลขนำหน้าผิดโดยเฉพาะเลขฐานสิบหก ("0x ... ")
// การลบบังคับให้ infinities ไปยัง NaN
ฉันคิดว่าเราสามารถวางใจได้ว่า chaps เหล่านี้ใช้เวลากับเรื่องนี้ไม่น้อย!
ฉันสงสัยว่าทำไมไม่มีใครโพสต์วิธีแก้ปัญหาเช่น:
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';
}
หากคุณกำลังทดสอบอักขระเดี่ยวให้ทำดังนี้
var isDigit = (function() {
var re = /^\d$/;
return function(c) {
return re.test(c);
}
}());
จะคืนค่าจริงหรือเท็จขึ้นอยู่กับว่า c เป็นตัวเลขหรือไม่
ฉันขอแนะนำ regex ง่ายๆ
หากคุณกำลังมองหาเพียงอักขระสุดท้ายในสตริง:
/^.*?[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
และ regex นั้นง่ายกว่าถ้าคุณแค่ตรวจสอบ char เดียวเป็นอินพุต:
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;
หากคุณต้องการตรวจสอบมากกว่า 1 แชทเตอร์คุณอาจใช้ตัวแปรถัดไป
นิพจน์ทั่วไป:
const isDigit = n => /\d+/.test(n);
เปรียบเทียบ:
const isDigit = n => +n == n;
ตรวจสอบว่าไม่ใช่ NaN
const isDigit = n => !isNaN(n);
var Is = {
character: {
number: (function() {
// Only computed once
var zero = "0".charCodeAt(0), nine = "9".charCodeAt(0);
return function(c) {
return (c = c.charCodeAt(0)) >= zero && c <= nine;
}
})()
}
};
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
ลอง:
function is_numeric(str){
try {
return isFinite(str)
}
catch(err) {
return false
}
}
ฉันใช้คล้ายกับหนึ่งในคำตอบข้างต้น
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
บล็อกโพสต์นี้ให้ความกระจ่างมากขึ้นในการตรวจสอบว่าสตริงเป็นตัวเลขใน Javascript | หรือไม่ typescript และ ES6
วิธีง่ายๆโดยใช้ประโยชน์จากการตรวจสอบประเภทไดนามิกของภาษา:
function isNumber (string) {
//it has whitespace
if(string.trim() === ''){
return false
}
return string - 0 === string * 1
}
ดูกรณีทดสอบด้านล่าง
ดูเหมือนว่าจะได้ผล:
การผูกแบบคงที่:
String.isNumeric = function (value) {
return !isNaN(String(value) * 1);
};
การผูกต้นแบบ:
String.prototype.isNumeric = function () {
return !isNaN(this.valueOf() * 1);
};
จะตรวจสอบอักขระเดี่ยวและสตริงทั้งหมดเพื่อดูว่าเป็นตัวเลขหรือไม่
square = function(a) {
if ((a * 0) == 0) {
return a*a;
} else {
return "Enter a valid number.";
}
}
function is_numeric(mixed_var) {
return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
mixed_var !== '' && !isNaN(mixed_var);
}
คุณสามารถลองสิ่งนี้ (ใช้ได้ในกรณีของฉัน)
หากคุณต้องการทดสอบว่าอักขระตัวแรกของสตริงเป็น int หรือไม่:
if (parseInt(YOUR_STRING.slice(0, 1))) {
alert("first char is int")
} else {
alert("first char is not int")
}
หากคุณต้องการทดสอบว่าถ่านเป็น 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)
เท่าที่ฉันรู้วิธีที่ง่ายที่สุดคือการคูณด้วย1:
var character = ... ; // your character
var isDigit = ! isNaN(character * 1);
การคูณด้วยหนึ่งจะทำให้ได้ตัวเลขจากสตริงตัวเลขใด ๆ (เนื่องจากคุณมีอักขระเพียงตัวเดียวมันจะเป็นจำนวนเต็มตั้งแต่ 0 ถึง 9 เสมอ) และ a NaNสำหรับสตริงอื่น ๆ
เพียงแค่ใช้ isFinite
const number = "1";
if (isFinite(number)) {
// do something
}