9 Big data type

Odd values in numbers:

  • NaN: Not a significant number, but of type number. IsNaN checks whether the value is a NaN. If the current value is not a Number, it is implicitly converted to a Number (Number conversion), and then determines whether it is a valid Number. Object.is(NaN, NaN) can also check if the value is NaN

Data type conversion

In the front-end type conversion, there are two types: manual conversion and implicit conversion

The other types are converted to the Number type

  • Manual switch

    • Number([val])
    • parseInt/parseFloat([val])
  • Implicit conversion (internal browser default is first converted to Number before calculation)

    • isNaN([val])
    • Number operations (+, -, *, /, %), but the + operation is not a number operation in the case of strings, it is string concatenation
    • Some values need to be converted to numbers during the == comparison

Number conversion

Number(" ') => 0 Number('10') => 10 Number('10px') => NaN Number(null) => 0 Number(undefined) => NaN Number(Symbol(1)) => Error Number(BigInt(1)) => 1 Converting an object to a number => First converts the object to a primitive type based on the valueOf method. No primitive type is converted to a string based on toString, and a string is converted to a numberCopy the code

ParseInt/parseFloat conversion

ParseInt conversion mechanism (parseFloat is similar, but recognizes one more decimal point) :

  1. Find a significant number starting with the first string to the left of the string.
  2. Stop the search when it encounters a non-significant digit character, regardless of whether there is a significant digit following.
  3. Converts a valid numeric character found to a number.
  4. If a valid numeric character is not found, the result is NaN.

Look at some examples of interview questions from a large company: What is the output?

parseInt(''); Number(''); isNaN(''); parseInt(null); Number(null); isNaN(null); parseInt('1px'); Number('1px'); isNan('1px'); ParseInt ('1.1px') + parseFloat('1.1px') + Typeof parseInt(null); isNaN(Number(!! Number (parseInt (' 1.8 ')))); typeof ! parseInf(null) + ! isNaN(null); 1 + false + undefined + [] + 'Tencent' + null + true + {};Copy the code

ParseInt () :

Let arr = [1, 2, 3, 4]; arr = arr.map(parseInt); console.log(arr);Copy the code

ParseInt ([value], [radix])

  • Radix this value is base, default to base 10 if not written or 0 written (special case: default to 10 or 16 if value starts with 0x).
  • The base has a range of values between 2 and 36, if not, the entire program must run as NaN.
  • [value] is the [radix] base value, which needs to be converted to decimal.
arr.map(parseInt)
=> 
parseInt('1', 0);  => 1
parseInt('2', 1);  => NaN
parseInt('3', 2);  => NaN
parseInt('4', 3);  => NaN
=> [1, NaN, NaN, NaN]
Copy the code

Implicit conversion

Look at a simple example:

[] == false;
Copy the code

The comparison between an object and a Boolean is that it is converted to a number (implicit conversion). An object is converted to a number based on valueOf, and if there is no original value in toString it is converted to a string and then converted to a number.

In the example above:

  1. [] Obtain the original value based on valueOf, [].valueof () => [], find that [] has no original value.
  2. ToString () => “. ToString () => “.
  3. “Converts to a number of 0.
  4. False converts to a number 0.
  5. So [] == false => true

Look at an extended example:

! [] == false;Copy the code
  1. The comparison here first looks at the symbol priority,! Is higher than ==, so yes! The result of [] is compared with false.
  2. ! The underlying meaning of [] is to convert [] to the inverse of a Boolean.
  3. In js, ”, 0, null, undefined, NaN become Boolean false, the other values are true, so [] converts to Boolean true. ! [] = > false.
  4. ! The [] == false construct is true.

The rules for converting objects call the built-in [ToPrimitive] function first, and the rule logic is as follows:

  • If the Symbol. ToPrimitive method is deployed, call it first and return it.
  • Calls valueOf(), which returns if converted to an underlying type;
  • Call toString(), which returns if cast to base type;
  • If none of the underlying types are returned, an error is reported.

The other types are converted to String

  • Manual switch

    • String([val])
    • toString()
  • Implicit conversion

    • + operation, string concatenation if a string appears on one side.
    • There is a special case where an object’s + (for example, 1+[]) becomes a string concatenation, because the object is converted to a string first, and + becomes a string concatenation when it encounters a string.
    • It’s not necessarily a string concatenation for +/++, it’s an operation.
    • There is also a special case {} + 0 where the left-hand side looks like an object, but is treated as a code block. So this is the number 0.
    • To convert an object to a number, toString() is first converted to a string and then to a number

Other types are cast to Boolean types

  • Manual switch
    • ! [val]
    • !!!!! [val]
    • Boolean([val])
  • Implicit conversion
    • In loops or conditional judgments, the result of conditional processing is a Boolean value

Data type detection

The first judgment method: Typeof

typeof 1 => 'number'
typeof '1' => 'string'
typeof treu => 'boolean'
typeof undefined => undefined
typeof null => 'object'
typeof Symbol(1) => 'symbol'
typeof 1n => 'bigint'
typeof []  =>'object'
typeof {}  =>'object'
typeof console  => 'object'
typeof console.log  => 'function'
Copy the code

There are two things to note about typeof:

  1. Typeof null results in ‘object’. This is caused by a Bug in the computer.

The “typeof NULL” error is a holdover from the first version of JavaScript. In this version, values are stored in 32-bit cells consisting of a type label (1-3 bits) and the actual data for the value. The type label is stored in the lower level of the cell. There are five of them:

  • 000: object
  • 1: the integer
  • 010: floating point number
  • 100: string
  • 110: Boolean value

That is, the lowest bit is one, so the type token is only one bit long. Or it is zero, then the length of the type label is three digits, providing two extra bits for the four types. There is one value in particular:

  • Undefined is an integer -2 ^30 (numbers outside the integer range)
  • Null is the machine code null pointer. An object type label with a reference to zero. This is obvious why typeof NULL results in ‘object’.

And in ECMA6, there was a proposal that was historically trivial, and the value of type NULL was corrected to ‘NULL’, but the proposal was rejected. The reason is that there is too much legacy code.

  1. Reference to the data type Object, all but function are ‘Object’ when using typeof. This is also one of the reasons why it is necessary to distinguish object from function when classifying types.

Typeof can determine underlying data types (except null), but reference data types other than function types cannot be determined.

The second judgment method: instanceof

[value] instanceof [constructor]

The instanceof operator checks whether [value] has a [constructor] prototype property in its prototype chain.

Function myInstanceof(left, right) {// Return false if(typeof left! == 'object' || left === null) return false; Let proto = object.getProtoTypeof (left); let proto = object.getProtoTypeof (left); If (proto === null) return false; if(proto == null) return false; If (proto === right.prototype) return true; Proto = object.getProtoTypeof (proto); }}Copy the code

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

The third method of judgment: constructor

[value].constructor === class. Primitive types can be handled as opposed to instanceof. But constructor can be modified at will.

A fourth judgment method: Object. The prototype. ToString

ToString () is an Object prototype method that returns uniformly a string of the format “[Object Xxx]”, where Xxx is the type of the Object. For Object objects, toString() returns [Object Object]; Other objects need to be called by call to return the correct type information.

Object.prototype.toString({}) => "[object Object]" Object.prototype.toString.call({}) => "[object Object]" 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(/123/g) => "[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]"Copy the code

Through the Object. The prototype. ToString can realize a type of passing judgment method:

function getType(obj){ let type = typeof obj; Return if (type!) if (type! == "object") { return type; } / / for the typeof returns the result is that the object, then the following judgment, regular return results return object. The prototype. ToString. Call (obj). Replace (/ ^ [object (\ S +)] $/, "$1"); }Copy the code

In ES3, when the toString method is called, the following steps are performed:

  1. Gets the value of the [[Class]] property of this.
  2. Evaluates the three strings “[object “, the Result of the first step, Result(1), and the new string concatenated by “]”.
  3. Returns Result(2) of the second step.

In ES5, when the toString method is called, the following steps are performed:

  1. If this is undefined, “[object undefined]” is returned.
  2. If the value of this is null, “[object null]” is returned.
  3. Get Result(1) of ToObject(this).
  4. Get the value Result(2) of the internal attribute [[Class]] of Result(1).
  5. Returns three strings “[object “, Result(2), and a new string concatenated with “]”.

reference

  • www.zhihu.com/question/21…
  • Developer.mozilla.org/zh-CN/docs/…
  • 2 ality.com/2013/10/typ…
  • Kaiwu.lagou.com/course/cour…