Home  >  Article  >  Web Front-end  >  How to determine whether a variable is a string in es6

How to determine whether a variable is a string in es6

青灯夜游
青灯夜游Original
2022-04-11 15:47:253196browse

Judgment method: 1. Use the "typeof variable === 'string'" statement; 2. Use "variable instanceof String"; 3. Use "Object.prototype.toString.call(variable)=== "[object String]"".

How to determine whether a variable is a string in es6

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

es6 Determine whether a variable is a string

Method 1: Use the typeof keyword

## The syntax rules for #typeof are:

typeof operand.

We can directly use

typeof a === 'string' to judge. If the return value is true, it is a string.

Example:

var a="123456";
typeof a === 'string';

var b=123456;
typeof b === 'string';

How to determine whether a variable is a string in es6

In addition, list some special cases of this operator:

typeof Null; // 'object'
typeof NaN; // 'number'
typeof Array; // 'object'

Method 2: Using the instanceof keyword

The syntax rule for instanceof is

object instanceof constructor. The return value is of type boolean.

instanceof works by checking whether the

prototype property of the constructor exists on the prototype chain of the object. This means that it can only determine the object type.

If we use new String("I am string") to construct a string, we can also use instanceof to judge. As follows:

new String("I am string") instanceof String;

How to determine whether a variable is a string in es6

Method 3: Object.prototype.toString.call()

This method will return "## by default #[object type]

", where type is the type of data. It is worth mentioning that call must be used when we call. <pre class="brush:php;toolbar:false">var a=&quot;123456&quot;; Object.prototype.toString.call(a) === &quot;[object String]&quot;; var b=123456; Object.prototype.toString.call(b) === &quot;[object String]&quot;;</pre>

How to determine whether a variable is a string in es6[Related recommendations:

javascript video tutorial

, web front-end

The above is the detailed content of How to determine whether a variable is a string in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn