Home  >  Article  >  Web Front-end  >  Sorting out JavaScript basic data

Sorting out JavaScript basic data

不言
不言forward
2019-02-28 13:16:072514browse

The content of this article is about sorting out the basic data of JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

After reading some information, combined with ES6, elevation and MDN, I sorted out the core knowledge points of JS. Due to limited space, I only introduce the knowledge that I think is important here. For some common sense things, you can refer to elevation, and for expansion of some core knowledge points, you can refer to my other articles. This article is suitable for review/surprise use of JS knowledge points, and can also be used as a front-end interview guide.

7 data types

Basic data type: stored in stack memory, operating on value

null: null pointer, so typeof null ==>Object

undefined: An unassigned value is defined

Number: Number

String: String

Symbol: An instance is a unique and immutable data type.

Boolean: Boolean value

Reference data type: stored in heap memory, operating on space address

Object: specifically it can be Array, Function, RegExp, Date

Judge the data type (method, pros and cons)

typeof: can only judge non-Null in the basic type, and cannot judge the reference data type (because all are objects)It is an operator

typeof ''  // ==> string
typeof 1  //==> number
typeof true  //==>boolean
typeof undefined  //==>undefined
let b = Symbol() ; typeof b //==>symbol
-----------------下面的判断不了实际类型了-----------------------
typeof function fn(){} //==>function
typeof null //==>object
typeof [1,2,3] //==>object
typeof {} //==>object

instanceof: used to test whether the prototype attribute of the constructor appears anywhere in the prototype chain of the object. You can use it to judge Array but it is not elegant enough and has certain risks

let arr = [1,2,3]
arr instanceof Array //==>true
arr instanceof Object //==>true
# The problem with the ##instanceof operator is that it has only one global execution environment. If the web page has multiple frames, there are actually more than two different global execution environments, and thus more than two different versions of the Array constructor. If an array is passed from one frame to another, then the incoming array and the array created natively in the second frame have different constructors----height page88 (The author's vernacular translation:
The risk comes from the rewriting of the prototype chain)
constructor: The principle is also based on the prototype chain, and the risk also comes from the rewriting of the prototype chain, such as when you shuttle back and forth between multiple frames At this time, these two methods are the best. Since each iframe has its own execution environment, objects instantiated across frames do not share the prototype chain with each other, thus causing the above detection code to fail!

isNaN:

This method will first call Number , so it’s not very useful

   console.log(isNaN("1px"));   //先调用Number('1px'),返回NaN,然后再调用isNaN(NaN)返回true
   //燃鹅 '1px'客观并不是NaN
rrree---------------------------------- -------------Better method--------------------------------

Object.prototype.toString.call()

    [1,2,3,1].constructor === Array; // true
-------------------------------- --------------------Elegant method---------------------

If you need to judge Array separately

    Object.prototype.toString.call(null) // ==> [object Null]
    Object.prototype.toString.call([]) // ==> [object Array]
If you need to judge null separately

Array.isArray([]) //==>true
6 ways to declare variables

ES5 has only two ways to declare variables: var command and function command . In addition to adding let and const commands, ES6 will also mention two other methods of declaring variables in later chapters: the import command and the class command. Therefore, ES6 has a total of 6 ways to declare variables. --es6
var: variable promotion, no block-level scope

When it comes to var, variable promotion must be mentioned: the current scope, before js (function) is executed, the browser will bring it var or function are declared and defined in advance

  1. Variables are only declared, functions are declared and assigned, and self-executing function definition and execution are completed together

  2. Not affected by logical judgment conditions

  3. return The following ones are also promoted, but the ones in return are not promoted

  4. Duplicate statements are OK, and reassignment is Yes, but the variable and method names cannot conflict

const: constant, the address remains unchanged, but the attributes can be changed

let: block scope, temporary dead zone ( TDZ), no variable promotion, repeated declarations are not allowed

let a = null
Object.is(a , null) //==>true

import:es6 modular solution

class:es6 inheritance solution

Type conversion

This section has too much content and is too complicated. In fact, I don’t really want to write it because few people can write code like this. But this is so important and must be tested in interviews. It is recommended that everyone master the core content and principles of this area and do not pay attention to weird tricks.

1. Automatic packaging

Three packaging types: Number, Boolean, String

//只要块级作用域内存在let命令,它所声明的变量就“绑定”(binding)这个区域,不再受外部的影响。所以下面代码不报错,外层作用域和里层作用域都有一个tmp
let tmp = 123;
    if (true) {
      let tmp =123;    
    }
//ES6 明确规定,如果区块中存在let和const命令,这个区块对这些命令声明的变量,从一开始就形成了封闭作用域。凡是在声明之前就使用这些变量,就会报错。
    let tmp = 123;
    if (true) {
      tmp = 'abc'; // ReferenceError
      let tmp;    
    }

These types (constructors) basically rewrite their tostring method

2. Forcibly convert to number

  • Number: Force the value of other data types into number type;

let s1 = '123'
let s2 = s1.slice(2)         // a是基本类型,它是没有slice方法的这里实际上后台完成了一个自动装包
---下面是实际发生的事---------
let s1 = new string('123')
let s2 = s1.slice(2)     
s1 = null      //注意这里用完就销毁了

//所以如果添加某个属性后面是调用不出来的
let s1 = '123'
s1.color = 'red'
console.log(s1.color) // ==> undefind
  • parseInt: A method often used to extract numbers from strings; identify the string from left to right until it encounters a non-valid number, stop, and return the found number. ;

    console.log(Number({}));//NaN
    console.log(Number(null));// 0
    console.log(Number(undefined));// NaN
    console.log(Number([]));// 0
    console.log(Number(""));// 0
    console.log(Number(true));// 1
    console.log(Number(false));
  • toFixed: method to retain the number of decimal points,

    The return value is a string;

  console.log(parseInt("12px12"));// 12
  console.log(parseInt("12.666.777px12"));// 12
  console.log(parseInt("px12.666px12"));// NaN
  console.log(parseInt(""));// NaN
  console.log(parseInt(true));// NaN
  console.log(parseInt({}));// NaN
  console.log(parseInt([]));// NaN
  console.log(parseInt(null));// NaN
  console.log(parseInt(undefined));// NaN
3.-Conversion

will first convert the string into a number (

Number), and then perform the calculation. Note that any calculation involving NaN, undiffed will Is it NaN

    console.log(Number("1px"));   //==> NAN
    console.log(parseInt("1px"));   //==> 1
    console.log(parseInt("p1px"));   //==> NaN

4. Conversion

Please see the table below for specific call string or number

            || undefined | null   | boolean | number | string | object |
=========================================================================
 undefined  || number    | number | number  | number | string | string | 
 null       || number    | number | number  | number | string | string | 
 boolean    || number    | number | number  | number | string | string | 
 number     || number    | number | number  | number | string | string | 
 string     || string    | string | string  | string | string | string | 
 object     || string    | string | string  | string | string | string |
    //字符串和任何类型相加都是调用String
    var  a = typeof 10 + true + [] + null + undefined+{};
    console.log(a); //==>numbertruenullundefined[object Object],{}
    console.log("6px"+undefined); ==> 6pxundefined
    console.log(NaN+"undefined");==> NaNundefined
    //经典面试题
    [1,2]+[2,1]  //==>都调用toString '1,2'+'2,1'===>'1,22,1'

5.布尔值Boolean

其他数据类型转布尔类型是false有且只有五个值: 0  ""  NaN null  undefined  
所以boolean({}) 或者boolean([]) 都是真

6.==和===

===是全等,==是类型转化后再判断,规则比较复杂。这里我认为除了准备面试需要看看,平时基本不会用,所以这个知识性价比非常低,学了用不到也会忘,大家自己把握,详细规则可以搜我其他文章
平时除了判断a是否是undefined或者是null(jq源码里面都用法)都时候其他情况下都用===

console.log(null==undefined) // true
console.log(undefined==undefined) // true


The above is the detailed content of Sorting out JavaScript basic data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete