Table of Contents
7 data types
Judge the data type (method, pros and cons)
5.布尔值Boolean
6.==和===
Home Web Front-end JS Tutorial Sorting out JavaScript basic data

Sorting out JavaScript basic data

Feb 28, 2019 pm 01:16 PM
javascript front end interview

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
Copy after login

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
Copy after login
# 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
Copy after login
rrree---------------------------------- -------------Better method--------------------------------

Object.prototype.toString.call()

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

If you need to judge Array separately

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

Array.isArray([]) //==>true
Copy after login
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
Copy after login

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;    
    }
Copy after login

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
Copy after login
  • 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));
Copy after login
  • 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
Copy after login
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
Copy after login

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 |
Copy after login
    //字符串和任何类型相加都是调用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'
Copy after login

5.布尔值Boolean

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

6.==和===

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

console.log(null==undefined) // true
console.log(undefined==undefined) // true
Copy after login


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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Golang framework interview questions collection Golang framework interview questions collection Jun 02, 2024 pm 09:37 PM

The Go framework is a set of components that extend Go's built-in libraries, providing pre-built functionality (such as web development and database operations). Popular Go frameworks include Gin (web development), GORM (database operations), and RESTful (API management). Middleware is an interceptor pattern in the HTTP request processing chain and is used to add functionality such as authentication or request logging without modifying the handler. Session management maintains session status by storing user data. You can use gorilla/sessions to manage sessions.

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Selected Java JPA interview questions: Test your mastery of the persistence framework Selected Java JPA interview questions: Test your mastery of the persistence framework Feb 19, 2024 pm 09:12 PM

What is JPA? How is it different from JDBC? JPA (JavaPersistence API) is a standard interface for object-relational mapping (ORM), which allows Java developers to use familiar Java objects to operate databases without writing SQL queries directly against the database. JDBC (JavaDatabaseConnectivity) is Java's standard API for connecting to databases. It requires developers to use SQL statements to operate the database. JPA encapsulates JDBC, provides a more convenient and higher-level API for object-relational mapping, and simplifies data access operations. In JPA, what is an entity? entity

See all articles