Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How much do you know about the data types of JavaScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

JavaScript data type you know how much, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Preface

As the entry point of JavaScript, Js data type is particularly important in the whole learning process of JavaScript. The most common problem is the judgment of boundary data type conditions.

Concept

Undefined, Null, Boolean, String, Number, Symbol, BigInt are the basic types

Object is a reference type, which includes several common types such as Array, RegExp, Date, Math, and Function.

Data types are roughly divided into two categories for storage.

The underlying type is stored in stack memory, and when referenced or copied, an identical variable is created.

Reference types are stored in heap memory, where addresses are stored, and multiple references point to the same address, which involves the concept of "sharing".

Example question 1:

Let a = {name: "maomin", age: "20"} let b = a; console.log (a.name); / / "maomin" b.name = "haojie"; console.log (a.name); / / "haojie" console.log (b.name); / / "haojie"

This reflects the "sharing" nature of the reference type, that is, both values are shared in the same block of memory, one changes, and the other changes accordingly.

Example question 2:

Let a = {name: 'maomin', age: 20} function change (o) {o.age = 24; o = {name:' haojie', age: 30} return o;} let b = change (a); console.log (b.age); / / 30 console.log (a.age); / / 24

The o passed in by the function passes the value of the memory address of the object in the heap, which does change the age property of the an object by calling o.age = 24; but {name:'haojie',age:30} in the code changes o to another memory address, stores {name:'haojie',age:30}, and finally returns the value of b to {name:'haojie',age:30}.

In fact, the above two examples clearly illustrate that the data property must be a function rather than an object in a Vue.js component, and each instance can maintain a separate copy of the returned object.

Data type detection

The first detection method: typeof

Typeof 1 / / 'number' typeof' 1' / / 'string' typeof undefined / /' undefined' typeof true / / 'boolean' typeof Symbol () / /' symbol' typeof null / / 'object' typeof [] / /' object' typeof {} / / 'object' typeof console / /' object' typeof console.log / / 'function'

As you can see, the first six are basic data types, but why is the typeof of the sixth null object? I want to emphasize to you here that although typeof null outputs object, this is only a long-standing Bug of JS. It doesn't mean that null is a reference data type, and null itself is not an object. Therefore, null returns problematic results after typeof and cannot be used as a method to judge null. If you need to determine whether it is null in the if statement, just judge it directly through = null.

In addition, note that if you refer to the data type Object and use typeof to judge, except that function will correctly judge, the rest are object, which cannot be judged.

The second detection method: instanceof

If we new an object, then the new object is the object inherited by its prototype chain. Through instanceof, we can determine whether this object is the object generated by the previous constructor, so we can basically determine the data type of the new object.

Let Car = function () {} let benz = new Car (); benz instanceof Car; / / true let car = new String ('maomin'); car instanceof String; / / true let str =' haojie'; str instanceof String; / / false

We can implement an underlying implementation of instanceof ourselves:

Function myInstanceof (target, typeObj) {/ / here we first use typeof to determine the basic data type. If so, directly return false if (typeof target! = = 'object' | | target = null) return false; / / getProtypeOf is the API of the Object object, and the prototype object let proto = Object.getPrototypeOf (target) that can get parameters While (true) {/ / cycle down until you find the same prototype object if (proto = = null) return false; if (proto = = typeObj.prototype) return true;// finds the same prototype object and returns true proto = Object.getPrototypeof (proto);}} / / verify your own myInstanceof console.log (new String ('maomin'), String)) / / true console.log (myInstanceof ('maomin', String)); / / false

Seeing the implementation of the above code, we will summarize the differences between the two methods:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Instanceof can accurately judge complex reference data types, but can not correctly determine the underlying data types

Typeof also has drawbacks, although it can determine the underlying data type (except null), but the reference data type, except the function type, can not be determined.

The third detection method: Object.prototype.toString

ToString () is the prototype method of Object. By calling this method, you can uniformly return a string in the format "[object Xxx]", where Xxx is the type of object, and the first letter is capitalized. For Object objects, a direct call to toString () returns "[object Object]"; for other objects, you need to call through call to return the correct type information.

Object.prototype.toString ({}) / / "[object Object]" Object.prototype.toString.call ({}) / / same as above Plus call also ok Object.prototype.toString.call (1) / / "[object Number]" Object.prototype.toString.call ('1') / / "[object String]" Object.prototype.toString.call (true) / / "[object Boolean]" Object.prototype.toString.call (function () {}) / / "[object Function]" Object.prototype.toString.call (null) / / "[object Null]" Object.prototype .toString.call (undefined) / / "[object Undefined]" Object.prototype.toString.call (/ 123gamg) / / "[object RegExp]" Object.prototype.toString.call (new Date ()) / / "[object Date]" Object.prototype.toString.call ([]) / / "[object Array]" Object.prototype.toString.call (document) / / "[object HTMLDocument]" Object.prototype.toString.call (window) / / "[object Window]"

OK, next we will implement a complete method of data type detection.

Function getType (obj) {let type = typeof obj; if (type! = = "object") {/ / first make typeof judgment. If it is the basic data type, return return type;} / / if the result returned by typeof is object, then make the following judgment, then return the result return Object.prototype.toString.call (obj). Replace (/ ^\ [object (\ S+)\] $/,'$1') / / Note that there is a space} / * code verification in the middle of the rule. You need to pay attention to the case. Which are typeof judgments and which are toString judgments? Think about it * / getType ([]) / / "Array" typeof [] is object, so toString returns getType ('123') / / "string" typeof directly returns getType (window) / / "Window" toString returns getType (null) / / "Null" initials, typeof null is object Need toString to judge that getType (undefined) / / "undefined" typeof directly returns getType () / / "undefined" typeof directly returns getType (function () {}) / / "function" typeof can judge, so the initials getType (/ 123gamg) / / "RegExp" toString returns

Data type conversion

In daily business development, we often encounter the problem of JavaScript data type conversion, sometimes we need to take the initiative to cast, and sometimes JavaScript will carry out implicit conversion, implicit conversion requires us to pay more attention.

'123' = = 123 / / true''= = null / / false''= 0 / / true [] = 0 / / true [] ='/ / true [] = =! [] / / true null = = undefined / / true Number (null) / / 0 Number ('') / / 0 parseInt ('') / / NaN {} + 10 / 10 let obj = {[Symbol.toPrimitive] () {return 200;}, valueOf () {return 300;}, toString () {return 'Hello';}} console.log (obj + 200); / / 400

I believe the above code is no stranger to you, and basically covers some of the situations that we are easy to miss, that is, the casting and implicit conversion that we often encounter when doing data type conversion.

Forced type conversion

Forced type conversion methods include Number (), parseInt (), parseFloat (), toString (), String (), Boolean (), these methods are similar, through the literal meaning can be easily understood, are through their own methods to cast data types.

Cast rules for the Number () method

If it is a Boolean, true and false are converted to 1 and 0, respectively

If it is a number, return itself

If it is null, return 0

If it is undefined, return NaN

If it is a string, follow these rules: if the string contains only numbers (or a hexadecimal string starting with 0X / 0x, with plus or minus signs allowed), convert it to decimal; if the string contains a valid floating-point format, convert it to a floating-point value; if it is an empty string, convert it to 0; if it is not a string of the above format, return NaN

If it is Symbol, throw an error

If it is an object and [Symbol.toPrimitive] is deployed, call this method, otherwise call the object's valueOf () method, and then convert the returned value according to the previous rule; if the result of the transformation is NaN, call the object's toString () method and return the corresponding value again in the previous order.

Number (true); / / 1 Number (false); / / 0 Number ('0111'); / / 111 Number (null); / / 0 Number (''); / / 0 Number ('1a'); / / NaN Number (- 0X11); / /-17 Number (' 0X11') / / 17

Among them, the above listed the more common examples of Number conversion, they will convert the corresponding non-numeric types into digital types, and some can not be converted into numbers, and finally can only output the results of NaN.

Cast rules for the parseInt () method

Considering that converting strings with the Number () function is relatively complex and somewhat unconventional, the parseInt () function is usually preferred when you need to get integers. The parseInt () function focuses more on whether the string contains a numeric pattern. The first space in the string is ignored, starting with the first non-space character. If the first character is not a numeric character, plus sign, or minus sign, parseInt () immediately returns NaN. This means that the empty string also returns NaN (unlike Number (), which returns 0). If the first character is a numeric character, plus sign, or minus sign, continue to detect each character in turn until the end of the string, or encounter a non-numeric character. For example, "1234blue" will be converted to 1234 because "blue" will be completely ignored. Similarly, "22.5" is converted to 22 because the decimal point is not a valid integer character.

Assuming that the first character in the string is a numeric character, the parseInt () function also recognizes different integer formats (decimal, octal, hexadecimal). In other words, if the string begins with "0x", it is interpreted as a hexadecimal integer. If the string begins with "0" and is followed by a numeric character, it will be interpreted as an octal integer by some implementations in non-strict mode.

Let num1 = parseInt ("1234blue"); / / 1234 let num2 = parseInt (""); / / NaN let num3 = parseInt ("0xA"); / / 10, interpreted as hexadecimal integer let num4 = parseInt (22.5); / / 22 let num5 = parseInt ("70"); / / 70, interpreted as decimal value let num6 = parseInt ("0xf"); / / 15, interpreted as hexadecimal integer

Different numeric formats are easily confused, so parseInt () also takes a second parameter that specifies the base (binary number). If you know that the value to be parsed is hexadecimal, you can pass in 16 as the second parameter to parse correctly:

Let num = parseInt ("0xAF", 16);

In fact, if the hexadecimal argument is provided, the "0x" before the string can be omitted:

Let num1 = parseInt ("AF", 16); / 175let num2 = parseInt ("AF"); / / NaN

In this example, the first transformation is correct, while the second transformation fails. The difference is that the first time you pass in a binary number as an argument, it tells parseInt () to parse a hexadecimal string. The second transformation detects that the first character is a non-numeric character and automatically stops and returns NaN.

With the second parameter, the type of result obtained after the conversion can be greatly expanded. For example:

Let num1 = parseInt ("10", 2); / 2, let num2 = parseInt ("10", 8) in binary; / 8, let num3 = parseInt ("10", 10) in octal; / 10, let num4 = parseInt ("10", 16) in decimal; / 16, hexadecimal

Because not passing a base argument is tantamount to letting parseInt () decide how to parse, it is recommended that you always pass it the second parameter to avoid parsing errors. In most cases, decimal numbers should be parsed, and the second parameter should be passed in 10.

Cast rules for the parseFloat () method

The parseFloat () function works like the parseInt () function, detecting each character starting at position 0. Similarly, it parses to the end of the string or to an invalid floating-point numeric character. This means that the first occurrence of the decimal point is valid, but the second occurrence of the decimal point is invalid, when the remaining characters of the string are ignored. Therefore, "22.34.5" will be converted to 22.34.

Another difference with the parseFloat () function is that it always ignores the zero at the beginning of the string. Hexadecimal values always return 0. Because parseFloat () parses only decimal values, the base cannot be specified. Finally, if the string represents an integer (there is no decimal point or there is only a zero after the decimal point), parseFloat () returns an integer. Here are a few examples:

Let a = parseFloat (true); / / NaN let num1 = parseFloat ("1234blue"); / / 1234, resolve let num2 = parseFloat ("0xA") by integer; / / 0 let num3 = parseFloat ("22.5"); / / 22.5 let num4 = parseFloat ("22.34.5"); / / 22.34 let num5 = parseFloat ("0908.5"); / / 908.5 let num6 = parseFloat ("31.25 million"); / 31250000

Cast rules for the Boolean () method

With the exception of undefined, null, false,'', 0 (including + 0 mai mi 0) and NaN converted to false, all the others are true.

Boolean (0) / / false Boolean (null) / / false Boolean (undefined) / / false Boolean (NaN) / / false Boolean (1) / / true Boolean (13) / / true Boolean ('12') / / true

Cast rules for the toString () method

The only use of this method is to return the string equivalent of the current value. For example:

Let age = 11; let ageAsString = age.toString (); / / string "11" let found = true; let foundAsString = found.toString (); / / string "true"

The toString () method can be found in numeric, Boolean, object, and string values. (yes, string values also have a toString () method, which simply returns a copy of itself.) There is no toString () method for null and undefined values.

In most cases, toString () does not accept any parameters. However, when calling this method on a numeric value, toString () can take a base argument, a string representation of the base number to output the value. By default, toString () returns ten of the value

Binary string representation. By passing in parameters, you can get the binary, octal, hexadecimal, or any other valid base of the value.

A string representation of a number, such as:

Let num = 10; console.log (num.toString ()); / / "10" console.log (num.toString (2)); / / "1010" console.log (num.toString (8)); / / "12" console.log (num.toString (10)); / / "10" console.log (num.toString (16)); / / "a"

This example shows that when the base parameter is passed in, the string value output by toString () changes accordingly. The value 10 can be output as

Any numerical format. Note that by default (no parameters are passed), the output is the same as that of parameter 10.

Cast rules for the String () method

If you are not sure whether a value is null or undefined, you can use the String () transformation function, which always returns a string representing the corresponding type value. The String () function follows the following rules.

If the value has a toString () method, the method is called (no arguments are passed) and the result is returned.

If the value is null, return "null".

If the value is undefined, return "undefined".

Here are a few examples:

Let value1 = 10; let value2 = true; let value3 = null; let value4; console.log (String (value1)); / / "10" console.log (String (value2)); / / "true" console.log (String (value3)); / / "null" console.log (String (value4)); / / "undefined"

This shows the conversion of four values to strings: a numeric value, a Boolean value, a null, and a undefined. The conversion result for numeric and Boolean values is the same as the call to toString (). Because null and undefined do not have a toString () method, the String () method directly returns the literal text of these two values.

Adding an empty string "" to a value with the plus operator can also convert it to a string.

Implicit type conversion

Usually through logical operators (& &, | |,!), operators (+, -, *, /), relational operators (>,

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report