Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

types - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're dealing with literal notation, and not constructors, you can use 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.

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

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...