Determining Variable Type in JavaScript: Numeral or String
To ascertain the data type of a variable in JavaScript, specifically whether it's a number or a string, consider the following approaches:
Literal Notation and typeof Operator:
For variables initialized using literal notation (e.g., "Hello World" or 123), use the typeof operator:
typeof "Hello World"; // string typeof 123; // number
Constructor Usage and typeof Operator:
When creating variables using constructors (e.g., var foo = new String("foo")), keep in mind that `typeof may return "object" for these variables.
Underscore.js Library:
For a more comprehensive method, utilize the isString method from the underscore.js library:
var toString = Object.prototype.toString; _.isString = function (obj) { return toString.call(obj) == '[object String]'; }
This method will accurately return true for both string literals and strings created using the constructor:
_.isString("Jonathan"); // true _.isString(new String("Jonathan")); // true
By employing these techniques, you can effectively determine whether a JavaScript variable is a number or a string, regardless of its initialization method.
The above is the detailed content of How do you determine if a JavaScript variable is a number or a string?. For more information, please follow other related articles on the PHP Chinese website!