"[A] front-end engineers qualified list of self-test" - JavaScript basic types of variables and

Foreword

A few days ago, @ ConardLi I published an article called "[a] front-end engineers qualified list of self-test" article, only to find themselves in the knowledge that there are so many loopholes. There are also grateful to the author's share. As a result, I have sprouted control lists, records, and learn again, make yourself not so confused.

A, JavaScript foundation

1. JavaScript language provides several types (seven kinds)

基本数据类型(6种):string, number, boolean, null, undefined, symbol
引用数据类型(*):Object (万物皆对象...)
复制代码

What are the underlying data structures 2. JavaScript object is

散列表(哈希表)
复制代码

3. Application of type Symbol actual development, to achieve a simple manually Symbol

我已知使用的地方,组件属性(mixin 模式)、常量定义。
要手写必须先了解Symbol.
复制代码

Symbol

Feature Examples
function Symbol()
By calling the new keyword does not function new Symbol() => TypeError
instanceof point is false let a = Symbol('a');a instanceof Symbol => false
Return type "symbol" typeof Symbol() === 'symbol'
only Symbol() != Symbol()
You can pass parameters, toString to view Symbol('foo').toString() === 'Symbol(foo)'
Symbol not operational 'Im a' + Symbol('foo') => TypeError
Symbol rotation may explicitly Str and Bool, can not be transferred Num String(Symbol('foo')) || Boolean(Symbol('foo'))
Symbol properties can not be traversed by conventional methods (for in) no
Symbol.for ([desc]) provided the only Symbol Symbol.for('foo') === Symbol.for('foo')
Symbol.keyFor ([Symbol]) Find Symbol's key let a = Symbol.for('foo');Symbol.keyFor(a) === 'foo'

In addition, we need to look at Symbol's specifications .

Symbol ( [ description ] )

When Symbol is called with optional argument description, the following steps are taken:

  1. If NewTarget is not undefined, throw a TypeError exception. (不能 new)
  2. If description is undefined, let descString be undefined. ()
  3. Else, let descString be ToString(description).
  4. ReturnIfAbrupt (descString). (Error returns)
  5. A new new UNIQUE the Return Symbol value Whose [[Description]] value IS descString. (Symbol returns a unique value, the value is the value Description of descString)
(function (w) {
            // 10. 可以通过 Symbol.for 来设置全局唯一的 Symbol.  ( 核心: 做一个映射表即可 )
            let globalSymbolMap = {}
            
            // ok  1. 函数        ok3
            function MySymbol(description) {
                // ok  2. 无法使用 new 关键字
                if(this instanceof MySymbol)
                    throw new TypeError('MySymbol is not a constructor')

                // ok  3. instanceof 返回 false. 因此只能对象
                // err 4. 无法实现 typeof MySymbol() === 'symbol',
                // ok  5. 返回的对象不是同一个,当然不一样
                // ok  6. `Symbol('foo').toString() === 'Symbol(foo)'` 实现
                let symbol = Object.create({
                    toString() {
                        return 'MySymbol(' + ( this.__Description__ || '' )+ ')'
                    },
                    //ok  7. 运算会调用 valueOf , 覆写即可。
                    //ok  8. 可以显示转 String 和 Boolean, 不能转 Number (因为复写了 valueOf)
                    valueOf() {
                        throw new Error('Cannot convert a MySymbol value')
                    }
                })
                // err  9.无法做到无法被变遍历。 因为遍历对象是不确定的,对象的属性设置也是需要控制那个对象才可以。
                Object.defineProperties(symbol, {
                    '__Description__': {
                        value: description === undefined ? undefined : String(description),
                        writable: false,
                        enumerable: false,
                        configurable: false
                    }
                })

                return symbol
            }
            // 10 设置for
            Object.defineProperties(MySymbol, {
                for: {
                    value: function(desc) {
                        if (globalSymbolMap[desc])
                            return globalSymbolMap[desc]
                        globalSymbolMap[desc] = MySymbol()
                        return globalSymbolMap[desc]
                    },
                },
                // 11. 设置 keyFor
                keyFor: {
                    value: function(symbol) {
                        for(let key in globalSymbolMap)
                            if (symbol === globalSymbolMap[key])
                                return key
                    },
                }
            })

            w.MySymbol = MySymbol
        })(window)
复制代码

4. JavaScript variables specific forms of storage in memory

基本数据类型 和 引用数据类型。

内存中会被开辟两块地方,一个是栈区,一个是堆区。基本数据类型的值会放在栈,引用数据类型的值会放在堆,它在堆的地址会放在栈。

// 自己随便画的,大家不要喷我。。。。。
复制代码

The built-in objects corresponding to the basic type, and boxing and unboxing operation between them

之前有说过基本数据类型有6种。其中,Symbol 较为特殊。他必须通过 Symbol() 获取,因为没有拆箱和装箱。
复制代码
  • null => Null
  • undefined => Undefined

Only one value of the above two types, there is no method, and with no discussion.

  • number => Number
  • string => String
  • boolean => Boolean

Unboxing operations: valueOf () or toString ()

Packing: Calls the method of operation of the current data other operations (e.g., String.toFixed, String.substring).

6. appreciated value and reference type

根据第5题,值类型的数据直接存放在栈。引用类型在栈中存放了真实数据的地址
复制代码

7. The difference between null and undefined

表象:
    null: 是关键字,typeof null 是 object。
    undefined:是全局变量,为了用于区分空值和未定义而引入的。
复制代码

According to the authoritative guide js description:

null and undefined means "vacant value"

You can think of undefined is a vacancy level of unexpected system error or a similar value, and null is a program level, the normal or expected vacancies in the value of.

8. The judge can say at least three of the way JavaScript data types, as well as their strengths and weaknesses, how accurate judgments array type

  • typeof
    • Pros: Simple .... (do not know if it)
    • Disadvantages: not null and distinguish object and array,
  • the instanceof (if the instance variable is determined for a particular object)
    • 优点:null instanceof Object === false; [] instanceof Array === true;
    • Disadvantages: the basic data types can not distinguish
  • Object.prototype.toString.call (data) where, data of the reference
    • Advantages: can identify most types of
    • Disadvantages: not identify the specific reference data types have some differences (e.g., from Person defined function, returns the [object Object]).

9. Transformation of the scene and the implicit type conversion may occur, or how to avoid the ingenious application

The figure is "Javascript The Definitive Guide" About the data conversion table

Personal summary is

  • Other types of string +, the plus sign is to do string concatenation. Other types will be converted to digital values ​​are added to the string type.

    • "string" + 1 => "string1"
    • "string" + true => "stringtrue"
    • "string" + null => "stringnull"
    • "string" + undefined => "stringundefined"
    • "string" + [] => "string"
    • "string" + {} => "string[object object]"
  • number: general use what type, will turn Number.

    1. +/- front
    2. [+ - * /%] (arithmetic operator)
    3. [> <> = <= ==! = ===! ===] (relational operator)

    as follows:

    • +"1" => 1
    • -true => -1
    • 1 + true => 2
    • 1 + ["9"] => 19
    • 1 + [9] => 19
    • +[9] + 1 => 10
    • 1 + null => 1
    • 1 + {} => 1[object Object]

    Relational Operators

    • "2"> 10 => false // turn digital comparator
    • "2"> "10" => true // than the ASCII code
    • NaN == NaN => false
    • undefined == null => false

    See some epic pits examples

    • [] == 0 //true
    • ![] == 0 // true
    • [] == ![] // true
    • [] == [] // false
    • {} == !{} // false
    • {} == {} // false

The maximum number of 10. The cause of decimal precision loss occurs, JavaScript can store a maximum security numbers, JavaScript method to handle large numbers of ways to avoid the loss of precision

  • BACKGROUND: JS follows the IEEE 754 specification, double precision storage, occupying 64 bit, i.e. 8 bits. Although many of the seemingly finite data, the computer is indeed endless. For example, large integer, floating-point numbers. Computer only 0 and 1, so the inside of the decimal rounding, in which the computer will become "0 and rounding up 1" was.

  • Js maximum number which is 2 ^ 53. Reason: 64, represents a positive or negative 11 represents an exponent, 52 mantissa. 52 + 1 = 53

  • js inside the maximum security number is 2 ^ 53--1

  • In my own work, as if large numbers and are stored in the floating point high precision with String.

other

The article is wrong, please correct me, so as not to mislead you -

references

Reproduced in: https: //juejin.im/post/5cc94723f265da034c7036e6

Guess you like

Origin blog.csdn.net/weixin_34409822/article/details/91478803