[英]Check whether variable is number or string in JavaScript
Does anyone know how can I check whether a variable is a number or a string in JavaScript?有谁知道如何检查 JavaScript 中的变量是数字还是字符串?
If you're dealing with literal notation, and not constructors, you can use typeof :.如果您正在处理文字符号而不是构造函数,则可以使用typeof :。
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.如果您通过构造函数创建数字和字符串,例如
var foo = new String("foo")
,您应该记住typeof
可能返回foo
的object
。
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here ),检查类型的更简单的方法可能是使用underscore.js中的方法(可以在此处找到带注释的源),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true
for the following:这将为以下内容返回布尔值
true
:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
Best way to do that is using isNaN
+ type casting:最好的方法是使用
isNaN
+ 类型转换:
Updated all-in method:更新全押方法:
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
The same using regex:使用正则表达式相同:
function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }
------------------------
isNumber('123'); // true
isNumber('123abc'); // false
isNumber(5); // true
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber(' '); // false
The best way I have found is to either check for a method on the string, ie:我发现的最好方法是检查字符串上的方法,即:
if (x.substring) {
// do string thing
} else{
// do other thing
}
or if you want to do something with the number check for a number property,或者如果你想对数字属性做一些检查,
if (x.toFixed) {
// do number thing
} else {
// do other thing
}
This is sort of like "duck typing", it's up to you which way makes the most sense.这有点像“鸭子打字”,由您决定哪种方式最有意义。 I don't have enough karma to comment, but typeof fails for boxed strings and numbers, ie:
我没有足够的业力来评论,但 typeof 对盒装字符串和数字失败,即:
alert(typeof new String('Hello World'));
alert(typeof new Number(5));
will alert "object".将提醒“对象”。
You're looking for isNaN()
:您正在寻找
isNaN()
:
console.log(!isNaN(123)); console.log(!isNaN(-1.23)); console.log(!isNaN(5-2)); console.log(!isNaN(0)); console.log(!isNaN("0")); console.log(!isNaN("2")); console.log(!isNaN("Hello")); console.log(!isNaN("2005/12/12"));
See JavaScript isNaN() Function at MDN.请参阅 MDN 上的JavaScript isNaN() 函数。
Since ES2015 the correct way to check if a variable holds a valid number is Number.isFinite(value)
自 ES2015 以来,检查变量是否包含有效数字的正确方法是
Number.isFinite(value)
Examples:例子:
Number.isFinite(Infinity) // false
Number.isFinite(NaN) // false
Number.isFinite(-Infinity) // false
Number.isFinite(0) // true
Number.isFinite(2e64) // true
Number.isFinite('0') // false
Number.isFinite(null) // false
Check if the value is a string literal or String object:检查该值是字符串文字还是字符串对象:
function isString(o) {
return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}
Unit test:单元测试:
function assertTrue(value, message) {
if (!value) {
alert("Assertion error: " + message);
}
}
function assertFalse(value, message)
{
assertTrue(!value, message);
}
assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");
Checking for a number is similar:检查数字是类似的:
function isNumber(o) {
return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}
Try this,尝试这个,
<script>
var regInteger = /^-?\d+$/;
function isInteger( str ) {
return regInteger.test( str );
}
if(isInteger("1a11")) {
console.log( 'Integer' );
} else {
console.log( 'Non Integer' );
}
</script>
//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
//basic usage
is('String', 'test'); // true
is('Array', true); // false
Or adapt it to return an unknown type:或者调整它以返回未知类型:
function realTypeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
//usage
realTypeOf(999); // 'Number'
May 12, 2012 Update: Full example at Javascript: A Better typeof .
2012 年 5 月 12 日更新: Javascript: A Better typeof中的完整示例。
Best way to do this:最好的方法:
function isNumber(num) {
return (typeof num == 'string' || typeof num == 'number') && !isNaN(num - 0) && num !== '';
};
This satisfies the following test cases:这满足以下测试用例:
assertEquals("ISNUMBER-True: 0", true, isNumber(0));
assertEquals("ISNUMBER-True: 1", true, isNumber(-1));
assertEquals("ISNUMBER-True: 2", true, isNumber(-500));
assertEquals("ISNUMBER-True: 3", true, isNumber(15000));
assertEquals("ISNUMBER-True: 4", true, isNumber(0.35));
assertEquals("ISNUMBER-True: 5", true, isNumber(-10.35));
assertEquals("ISNUMBER-True: 6", true, isNumber(2.534e25));
assertEquals("ISNUMBER-True: 7", true, isNumber('2.534e25'));
assertEquals("ISNUMBER-True: 8", true, isNumber('52334'));
assertEquals("ISNUMBER-True: 9", true, isNumber('-234'));
assertEquals("ISNUMBER-False: 0", false, isNumber(NaN));
assertEquals("ISNUMBER-False: 1", false, isNumber({}));
assertEquals("ISNUMBER-False: 2", false, isNumber([]));
assertEquals("ISNUMBER-False: 3", false, isNumber(''));
assertEquals("ISNUMBER-False: 4", false, isNumber('one'));
assertEquals("ISNUMBER-False: 5", false, isNumber(true));
assertEquals("ISNUMBER-False: 6", false, isNumber(false));
assertEquals("ISNUMBER-False: 7", false, isNumber());
assertEquals("ISNUMBER-False: 8", false, isNumber(undefined));
assertEquals("ISNUMBER-False: 9", false, isNumber(null));
Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.这是一种基于通过添加零或空字符串将输入强制为数字或字符串的想法的方法,然后进行类型化的相等比较。
function is_number(x) { return x === x+0; }
function is_string(x) { return x === x+""; }
For some unfathomable reason, x===x+0
seems to perform better than x===+x
.由于某些深不可测的原因,
x===x+0
似乎比x===+x
表现更好。
Are there any cases where this fails?有没有失败的情况?
In the same vein:同样的:
function is_boolean(x) { return x === !!x; }
This appears to be mildly faster than either x===true || x===false
这似乎比
x===true || x===false
稍微快一点。 x===true || x===false
or typeof x==="boolean"
(and much faster than x===Boolean(x)
). x===true || x===false
或typeof x==="boolean"
(并且比x===Boolean(x)
快得多)。
Then there's also然后还有
function is_regexp(x) { return x === RegExp(x); }
All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question.所有这些都依赖于每个类型特有的“身份”操作的存在,该操作可以应用于任何值并可靠地产生所讨论类型的值。 I cannot think of such an operation for dates.
我想不出这样的日期操作。
For NaN, there is对于 NaN,有
function is_nan(x) { return x !== x;}
This is basically underscore's version, and as it stands is about four times faster than isNaN()
, but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber.这基本上是下划线的版本,目前比
isNaN()
快大约四倍,但下划线源中的评论提到“NaN 是唯一不等于自身的数字”并添加了对 _.isNumber 的检查。 Why?为什么? What other objects would not equal themselves?
还有哪些其他对象不等于它们自己? Also, underscore uses
x !== +x
--but what difference could the +
here make?此外,下划线使用
x !== +x
——但是这里的+
有什么区别呢?
Then for the paranoid:然后对于偏执狂:
function is_undefined(x) { return x===[][0]; }
or this或这个
function is_undefined(x) { return x===void(0); }
Simple and thorough:简单而彻底:
function isNumber(x) {
return parseFloat(x) == x
};
Test cases:测试用例:
console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));
console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));
I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.我认为将 var 转换为字符串会降低性能,至少在最新浏览器中执行的这个测试表明了这一点。
So if you care about performance, I would, I'd use this:所以如果你关心性能,我会,我会用这个:
typeof str === "string" || str instanceof String
for checking if the variable is a string (even if you use var str = new String("foo")
, str instanceof String
would return true).用于检查变量是否为字符串(即使您使用
var str = new String("foo")
, str instanceof String
也会返回 true)。
As for checking if it's a number I would go for the native: isNaN
;至于检查它是否是一个数字,我会选择本机:
isNaN
; function.功能。
Or just use the invert of isNaN()
:或者只是使用
isNaN()
的反转:
if(!isNaN(data))
do something with the number
else
it is a string
And yes, using jQuery's $.isNumeric()
is more fun for the buck.是的,使用 jQuery 的
$.isNumeric()
更有趣。
Can you just divide it by 1?你能把它除以1吗?
I assume the issue would be a string input like: "123ABG"我认为问题将是一个字符串输入,例如:“123ABG”
var Check = "123ABG"
if(Check == Check / 1)
{
alert("This IS a number \n")
}
else
{
alert("This is NOT a number \n")
}
Just a way I did it recently.只是我最近做的一种方式。
uh, how about just:呃,怎么样:
function IsString(obj) {
return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}
After further review many months later, this only guarantees obj
is an object that has the method or property name toLowerCase
defined.经过几个月后的进一步审查,这只能保证
obj
是一个定义了方法或属性名称toLowerCase
的对象。 I am ashamed of my answer.我为我的回答感到羞耻。 Please see top-voted
typeof
one.请查看投票
typeof
的类型之一。
jQuery uses this: jQuery 使用这个:
function isNumber(obj) {
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}
This solution resolves many of the issues raised here!这个解决方案解决了这里提出的许多问题!
This is by far the most reliable method I have used by far.这是迄今为止我使用过的最可靠的方法。 I did not invent this, and cannot recall where I originally found it.
这不是我发明的,也不记得我最初是在哪里找到它的。 But it works where other techniques fail:
但它适用于其他技术失败的地方:
// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
if (undefined === data ){ return 'Undefined'; }
if (data === null ){ return 'Null'; }
return {}.toString.call(data).slice(8, -1);
};
// End public utility /getVarType/
Example of correctness正确性示例
var str = new String();
console.warn( getVarType(str) ); // Reports "String"
console.warn( typeof str ); // Reports "object"
var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num ); // Reports "object"
var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list ); // Reports "object"
Jsut an FYI, if you're using jQuery you have仅供参考,如果您使用的是 jQuery,您有
$.isNumeric()
to handle this.来处理这个。 More details on http://api.jquery.com/jQuery.isNumeric/
有关http://api.jquery.com/jQuery.isNumeric/的更多详细信息
注意typeof
NaN
是... 'number'
typeof NaN === 'number'; // true
since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var)
.由于带有 typeof 的字符串为 '1234' 将显示 'string',并且永远不会发生相反的情况(typeof 123 将始终是数字),最好是使用简单的正则表达式
/^\-?\d+$/.test(var)
。 Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/
The important side of .test
is that it WON'T throw an exception if the var isn't an string, the value can be anything.或者更高级的匹配浮点数、整数和负数,
/^[\-\+]?[\d]+\.?(\d+)?$/
.test
的重要方面是它不会抛出如果 var 不是字符串,则异常,该值可以是任何值。
var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;
regex.test(val) // false
val = '1234';
regex.test(val) // true
val = '-213';
regex.test(val) // true
val = '-213.2312';
regex.test(val) // true
val = '+213.2312';
regex.test(val) // true
val = 123;
regex.test(val) // true
val = new Number(123);
regex.test(val) // true
val = new String('123');
regex.test(val) // true
val = '1234e';
regex.test(val) // false
val = {};
regex.test(val) // false
val = false;
regex.test(val) // false
regex.test(undefined) // false
regex.test(null) // false
regex.test(window) // false
regex.test(document) // false
If you are looking for the real type, then typeof alone will do.如果您正在寻找真正的类型,那么 typeof 就可以了。
@BitOfUniverse's answer is good, and I come up with a new way: @BitOfUniverse 的回答很好,我想出了一个新方法:
function isNum(n) {
return !isNaN(n/0);
}
isNum('') // false
isNum(2) // true
isNum('2k') // false
isNum('2') //true
I know 0
can't be dividend, but here the function works perfectly.我知道
0
不能被股息,但这里的功能完美。
typeof works very well for me in most case.在大多数情况下,typeof 对我来说效果很好。 You can try using an if statement
您可以尝试使用 if 语句
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
where x is any variable name of your choice其中 x 是您选择的任何变量名称
You can check the type of variable by using typeof
operator:您可以使用
typeof
运算符检查变量的类型:
typeof variable
The code below returns true for numbers and false for anything else:下面的代码对数字返回 true,对其他任何东西返回 false:
!isNaN(+variable);
the best way i found which also thinks of positive and negative numbers is from : O'Reilly Javascript and DHTML Cookbook :我发现的同时考虑正数和负数的最佳方法来自: O'Reilly Javascript and DHTML Cookbook :
function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString( );
for (var i = 0; i < str.length; i++) {
oneChar = str.charAt(i).charCodeAt(0);
// OK for minus sign as first character
if (oneChar = = 45) {
if (i = = 0) {
continue;
} else {
alert("Only the first character may be a minus sign.");
return false;
}
}
// OK for one decimal point
if (oneChar = = 46) {
if (!oneDecimal) {
oneDecimal = true;
continue;
} else {
alert("Only one decimal is allowed in a number.");
return false;
}
}
// characters outside of 0 through 9 not OK
if (oneChar < 48 || oneChar > 57) {
alert("Enter only numbers into the field.");
return false;
}
}
return true;
} }
Errr?错了? Just use regular expressions!
只需使用正则表达式! :)
:)
function isInteger(val) {
return val.match(/^[0-9]$/)
}
function isFloat(val) {
return val.match(/^[0-9]*/\.[0-9]+$/)
}
function IsNumeric(num) {
return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}
XOR operation can be used to detect number or string. XOR 操作可用于检测数字或字符串。 number ^ 0 will always give the same number as output and string ^ 0 will give 0 as output.
number ^ 0 将始终给出与输出相同的数字,而 string ^ 0 将给出 0 作为输出。
Example:
1) 2 ^ 0 = 2
2) '2' ^ 0 = 2
3) 'Str' ^ 0 = 0
Simply use只需使用
myVar.constructor == String
or或者
myVar.constructor == Number
if you want to handle strings defined as objects or literals and saves you don't want to use a helper function.如果您想处理定义为对象或文字的字符串并保存您不想使用辅助函数。
Very late to the party;聚会很晚; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.
但是,当我想一次性检查某个输入是字符串还是数字时,以下内容对我来说一直很有效。
return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
Created a jsperf on the checking if a variable is a number.在检查变量是否为数字时创建了一个 jsperf。 Quite interesting!
很有趣! typeof actually has a performance use.
typeof 实际上有性能用途。 Using
typeof
for anything other than numbers, generally goes a 1/3rd the speed as a variable.constructor
since the majority of data types in javascript are Objects;将
typeof
用于除数字之外的任何内容,通常是variable.constructor
速度的 1/3,因为 javascript 中的大多数数据类型都是对象; numbers are not!数字不是!
http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number
typeof variable === 'number'
| typeof variable === 'number'
| fastest |最快的 | if you want a number, such as 5, and not '5'
如果你想要一个数字,比如 5,而不是 '5'
typeof parseFloat(variable) === 'number'
| typeof parseFloat(variable) === 'number'
| fastest |最快的 | if you want a number, such as 5, and '5'
如果你想要一个数字,比如 5 和 '5'
isNaN()
is slower, but not that much slower. isNaN()
较慢,但并没有那么慢。 I had high hopes for parseInt
and parseFloat
, however they were horribly slower.我对
parseInt
和parseFloat
寄予厚望,但是它们的速度非常慢。
For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant: 为了检测数字,以下来自JavaScript的段落:Douglas Crockford的The Good Parts是相关的:
The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity .
isFinite函数是确定某个值是否可以用作数字的最佳方法,因为它拒绝NaN和Infinity。 Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number.
不幸的是,isFinite会尝试将其操作数转换为数字,因此,如果值实际上不是数字,则不是一个很好的测试。 You may want to define your own isNumber function:
您可能需要定义自己的isNumber函数:
var isNumber = function isNumber(value) { return typeof value === 'number' &&
isFinite(value);
};
What do you thing about this one? 您对此有什么看法?
const numberOrString='10'
const isNumber = !isNaN(numberOrString*1)
I know which way I'll be using...我知道我将使用哪种方式...
![]()
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) } function isNumberRE(n) { return \/^-?[\\d.]+(?:e-?\\d+)?$\/.test(n); } function test(fn, timerLabel) { console.time(timerLabel) for (i = 0; i < 1000000; i++) { const num = Math.random() * 100 const isNum = fn(num) } console.timeEnd(timerLabel) } test(isNumber, "Normal way") test(isNumberRE, "RegEx way")<\/code><\/pre>
Normal way: 25.103271484375 ms RegEx way: 334.791015625 ms<\/code><\/pre>"
Like others, I'm addicted to strong typing (even though I love JS)和其他人一样,我沉迷于强类型(尽管我喜欢 JS)
And in my code, I happened to need to make a distinction between a number and a string, to perform 2 very different types of operations.在我的代码中,我碰巧需要区分数字和字符串,以执行两种截然不同的操作。
Rather than a spiel log:而不是高谈阔论的日志:
let int = 123, str = '123'; console.log( int.constructor===Number, str.constructor===String ); // true true console.log( typeof int === 'number', typeof str === 'number'); // true false console.log (Number(int)===int, Number(str)===str ) // true false // or: console.log (String(int)===int, String(str)===str ) // false true // the shortest: console.log( +int===int, +str===str ); // true false
I therefore mainly use, especially in ternary tests.因此,我主要使用,尤其是在三元测试中。
let res = (+X===X) ? stuff_to_do_with_a_Number(X) : stuff_to_do_with_a_String(X);
Of course, this must be handled with care.当然,这必须小心处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.