In daily development, every value defined by Js belongs to a certain data type. Common Js data types include String, Number, Boolean, Object, Undefined, Null, Symbol and so on. Symbol, a new data type introduced in ES6, represents a unique value. Because JS is a weakly typed language, type conversions occur frequently. This article aims to help you sort out the conversions between various types. Before each section explains conversions, we will introduce you to these “old friends”.

Data conversion is divided into display conversion and implicit conversion

  • ☀️ display conversions: common ️ explicit conversions are: Boolean(), Number(), String(), and so on
  • 🌛 Implicit conversion: Common implicit conversion methods: four operations (addition, subtraction, multiplication and division), ==, judgment statement (if), etc

1.String

String is a variable that stores characters. String uses the length attribute length to calculate the length of the String

1.1 Converting a String to a Number

  • parseInt(string, 10)

The parseInt() function parses a string, looking at each character starting at position 0 until the first invalid character is found, and finally returning an integer.

The parseInt() method also has a base mode that converts binary, octal, hexadecimal, or any other base string into integers. The base is specified by the second argument to the parseInt() method


  • parseFloat(string)

In contrast to the previous section, where parseInt converts a value to an integer, parseFloat converts a value to a floating-point number and has no base mode. These methods work only if they are called on a String


  • Number(string)

The cast of the Number() function is handled similarly to the parseInt() and parseFloat() methods, except that it converts the entire value instead of part of it

The parseInt() and parseFloat() methods mentioned in the previous two sections only convert the string before the first invalid character, so “1.2.3” will be converted to “1” and “1.2”, respectively. With Number(), “1.2.3” will return NaN, because the entire string value cannot be converted to a Number. If the string value can be converted completely


  • + string

By prefacing the string with a plus sign, the value becomes of type number


1.2 turn the String Object

Parse does this with json. parse, which raises a SyntaxError when it encounters a string that cannot be parsed.


1.3 Converting String to Object (Array Array Type)


2.Number

The Number type is expressed in ieEE-754 standard format, including integer and floating point numbers. If the Number is calculated, it is converted to base 2 and then computed. This is why 0.1 + 0.2 is not equal to 0.3

Extension: Why 0.1+0.2 does not equal 0.3 in JavaScript:

Console. log(0.1 + 0.2 == 0.3); //false
Copy the code

Because the binary floating-point numbers 0.1 and 0.2 in JavaScript are not very accurate, they do not add up to exactly 0.3, but a closer number 0.3000000x, so the conditional result is false.

Question: is there any way to solve the above problem ❓ you can use the minimum accuracy value provided by JavaScript number. EPSILON, within this error range you can determine 0.1+0.2===0.3 is true, as shown in 👇


In most cases, Number is better than methods like parseInt and parseFloat

2.1 turn Number String

  • n.toString( )

The toString() method converts a number to a string in the specified base form.


  • The unary operator +

The number becomes a string by adding an empty string after it


2.2 turn Boolean Number

Number type to Boolean, 0 and NaN correspond to false, all values correspond to true


3.Boolean

Boolean types have only two values :true and false. They are used to represent logical true and false Boolean types

All values are true except the following six values, which are converted to false


4.Object

Object is a more complex data type in JS, involving more things than other types. To simply describe an Object, it can be said to be a collection of data aggregated by key-value, namely, a collection of attributes. JS objects can be divided into two main categories, which are built-in objects and host objects

  • Built-in objects: JavaScript built-in objects are also defined as inner classes, in other words, JavaScript classes that are wrapped inside. Inner classes include: Array, Boolean,RegExp, Date, Math, Number, Stringnew Date();
  • Host object: objects provided by the environment in which JS runs, such as Window in BOM and Document in DOM

The data types of arrays, dates, null, and so on are all Object

The return value of the toString() method of different types of objects is also described here


Note: for example, 10 and new Number(10) are two different values. The former is of type Number and the latter is of object type

For another example, new Date and Date() yield the same result, but the built-in Date object, as a constructor new, produces a new object, and as a function, produces a string, as shown below 👇


4.1 Converting Object to String


4.2 Object Object to Object array

There are many ways to convert objects to arrays, including the following 👇

  • Object.values(Object) : Returns an array of values for all the enumerable attributes of an Object
  • Keys (Object) : Returns an array of an Object’s own enumerable properties
  • Object.entries(Object) : Returns an array of key-value pairs for a given Object’s own enumerable properties

Array.from() can also be used if an array-like object or traversable object is to be converted, but only if the object has a length property. The length of the Array returned depends on the length of the object, and the key of the object must be a numeric value

Kids 👦👧 do you have a lot of question marks? What are ❓ class objects?

An array-like object you can think of as a “pseudo-array” that doesn’t call array methods, but has a length property that indexes the data structure that retrieves the internal items

4.3 Date Object to Number

Convert a date object to a Number(in the form of a timestamp), either through Number() or the date method getTime()


4.4 Convert array Object to String

Join () can specify a delimiter using either the join or toString() methods. Without arguments, join() defaults to a comma delimiter, which is the same as the toString() conversion


[1,2,3,4] creates an object just like new Array(). New object a. “proto” == array.prototype

5 Undefind and Null

Null has only one value, and Undefined has only one value,Undefined has only one value. The difference is that Null means’ defined but the value is Null ‘whereas Undefind means’ there should be a value here but it is not defined yet’

Note that if we use typeof to determine the typeof null, we will evaluate it as Object, not null.

Because JavaScript data types are represented in binary form at the bottom, the first three bits of binary 0 will be identified as Object type by TypeOF, while the binary bits of null are exactly 0. Therefore, NULL is mistakenly identified as Object type. At this point we can use a section about through on the prototype of the Object’s toString () method, the following 👇 Object. The prototype. ToString. Call (null) / / / Object null to distinguish

5.1 Undefind and Null transform Number

Undefined cannot be converted to a number, while Null is converted to 0


Let’s look at another example 👇


Undefined cannot be converted to a number, and the first call returns NaN. The second is null, which translates implicitly to 0, so 2. The third is that if the argument passed is undefined, the default value will prevail, so 3

5.2 summarize

  • Do not assign undefined to an explicit variable. When you need to release an object, assign null
  • = =If two values in a double equal sign are of different types, they can be equal,undefind == nullIs one of them, including1 = = '1'But null and undefined are not valid if they are equal to other numbers because they do not perform type conversions (implicit conversions)

6.Symbol

Symbol is a new data type introduced in ES6 that represents a unique value. It is similar to an ID that indicates uniqueness. The Symbol function, however, is called directly with new, which raises an error because it generates a primitive value, not an object. The following simple use of an example can tell you how unique 👇


Symbol cannot be manipulated with other types of values and will report errors (that is, cannot be converted implicitly), but parts can be displayed converted to strings or Booleans


7. Develop

7.1 Type Determination method

If you use typeof to judge the data type, you can only distinguish the basic types, namely number, string, undefined, Boolean, object, function, symbol, etc., but for array, null, object, etc. Using Typeof returns “Object” uniformly. In this case, you need to use other methods 👇

Through Object. Protptype. ToString. Call () intercept string [Object]… The middle string to distinguish the type, remove the symbols before and after, such as “[object Array]” to extract the Array to judge, before writing the tool library has a definition point I 👉


It directly with the Object. The prototype. ToString (1) is that ok? The answer is no, because in order for every object to pass, it needs to be called as function.prototype.call (), passing the object to be checked as the first argument


For an example, see the following 👇


Why Object. Prototype and array. prototype are two results? There are some prototype chain issues involved here, and I’ll give you an overview of that

First of all, most objects in JS inherit from Object. When calling a method on an Object, the Object will be searched first. If no method is found, the Object’s prototype (.prototype) will be searched. Until object. prototype is found or entered at the top of the prototype chain.

Array.prototype.toString () {array.prototype. toString () {array.prototype. toString () {array.prototype. toString () {array.prototype. toString () {array.prototype. toString () {array.prototype. toString () {array.prototype. toString (); The third example toString(), because it calls array.prototype.tostring, is the same as the second.

Conclusion: Only Object. Prototype toString can be used to determine complex data types

The articles

  • Front-end form data stuff
  • Front-end engineering stuff
  • Develop tool libraries from 0 to 1
  • Develop simple scaffolding from 0 to 1
  • Front-end Nginx stuff
  • Front-end operations and deployment

Please drink a cup 🍵 remember three even oh ~

1. Remember to give 🌲 sauce a thumbs up after reading oh, there is 👍 motivation

2. Pay attention to the interesting things at the front of the public account, and chat with you about the interesting things at the front

3. Github frontendThings thanks to Star✨