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'客观并不是NaNrrree---------------------------------- -------------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([]) //==>true6 ways to declare variablesES5 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. --es6var: variable promotion, no block-level scopeWhen 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
- Variables are only declared, functions are declared and assigned, and self-executing function definition and execution are completed together
- Not affected by logical judgment conditions
- return The following ones are also promoted, but the ones in return are not promoted
- Duplicate statements are OK, and reassignment is Yes, but the variable and method names cannot conflict
let a = null
Object.is(a , null) //==>true
import:es6 modular solutionclass:es6 inheritance solutionType conversionThis 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 packagingThree 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
- 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));// NaN3.-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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.