01-First introduction to JavaScript

First introduction to JavaScript

1. First introduction to JavaScript

1.1.What is JavaScript

JavaScript ( JS ) is a A function-first lightweight, interpreted or just-in-time compiled programming language. Although it is best known as a scripting language for developing Web pages, it is also used in many non-browser environments, such as multi-paradigm dynamic scripting language that supports object-oriented, imperative and declarative (such as functional programming) styles . prototype-based programming. JavaScript is aAdobe Acrobat and Apache CouchDB, Node.js

1.2.Components of JavaScript
  • ECMAScript, describes the syntax and basic objects of the language.
  • Document Object Model (DOM) describes methods and interfaces for processing web content.
  • Browser Object Model (BOM), describing the methods and interfaces for interacting with Browser 6+.
1.3.History of JavaScript

In 1994, Netscape released version 0.9 of the Navigator browser. This was the first relatively mature web browser in history, and it was a sensation. However, this version of the browser can only be used for browsing and does not have the ability to interact with visitors. Netscape urgently needed a web scripting language that would allow browsers to interact with web pages.

In May 1995, Netscape made a decision that future web scripting languages ​​must "look similar enough to Java" but be simpler than Java so that non-professional web page authors can get started quickly. This decision actually excludes non-object-oriented programming languages ​​such as Perl, Python, Tcl, and Scheme.

​ JavaScript was originally designed by Brendan Eich of Netscape. The founder Brendan Eich designed JavaScript in only 10 days; the scripting language was initially named LiveScript, and later Netscape changed its name to JavaScript after cooperating with Sun. JavaScript was originally inspired by Java and was designed. One of the purposes is to "look like Java", so there are similarities in syntax, and some names and naming conventions are also borrowed from Java, but the main design principles of JavaScript are derived from Self and Scheme .

JavaScript was born in 1995. The main purpose at that time was to handle some unfilled required fields that were responsible for previous server languages, and whether invalid values ​​were entered. As the web became increasingly popular, people's demand for client-side scripting languages ​​became stronger and stronger. At that time, the vast majority of Internet users used cats with a speed of only 28.8kbit/s to surf the Internet, but the size and complexity of web pages continued to increase. Added, exchanging data with the server without completing simple form validation will only burden the user and server.

JavaScript development history

(1) JavaScript was originally named Mocha after it was designed. It was renamed in the Beta version of Netscape Navigator 2.0 in September 1995. LiveScript, which was renamed to JavaScript when deployed in Netscape Navigator 2.0 Beta 3 in December of the same year;

(2) IE 3 was released in August 1996, supporting jscript (js implemented by Microsoft)

(3) In November 1996, Netscape submitted the language standard to ECMA. Due to copyright issues, the js language standard was not called JavaScript, but ECMAScript.

(4) In June 1997, the first version of ECMAScript was released

(5) In December 1999, the third edition of ECMAScript was released. This version is the most widely used (the fourth edition was not successfully released)

(6) In 2006, jQuery was released. It is currently the longest-lived js library.

(7) In December 2009, the fifth edition of ECMAScript was released, adding some functions

(8) In 2009, Ryan created Node.js based on V8 (Chrome’s js engine is called V8)

(9) In 2010, Isaac wrote npm based on node.js

(10) In June 2015, the sixth version of ECMAScript was released, and new browsers support this version (thereafter, one version will be released every year, and the version number will be named after the year)

The rise of JavaScript: A language is needed that can run directly in the browser to complete form validation and reduce the pressure on the server

ECMAScript5: Programming (data structure, logic control, algorithm, memory allocation, advanced application BOM-Browser Object Model, DOM: Application API-Document Object Model)

In the early days, it mainly ran on the browser side and was used for form validation and animation implementation. With the upgrade of the js version, the current js can run on nodejs, and nodejs can be installed in most operating systems, so js can run on most systems, in addition to completing form verification and animation implementation You can also perform server-side programming and even hardware programming.

The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. On June 17, 2015, ECMA International released the sixth edition of ECMAScript. This version is officially called ECMAScript 2015, but is often called ECMAScript 6 or ES6.

It should be noted that js is different from Java. Java is developed and maintained by Sun Corporation and can only run in jdk. And js can run in most browsers. The mainstream browsers include IE, firefox, google chrome, safari... Will there be many versions of js like this? If so, wouldn't it be a mess: the JS code written by the programmer can run in Firefox, but there will be problems when running in IE. In fact, there was such a problem in the early days. Later, everyone felt that this would cause problems, so they sat together to discuss a unified grammar. Since the organization that formulated the grammar is called ECMA, the standard for JavaScript is ECMAScript. This ECMAScript What is in it is actually the basic syntax of variables, expressions, keywords...

JavaScript is a programming language that allows users to do complex things on browser pages. Browser pages are not always static, but often display content that needs to be dynamically updated, such as interactive maps, animations, and videos. A complete JavaScript includes core (ECMAScript), application programming interface (API) (such as DOM (Document Object Model), BOM (Browser Object Model)), and other third-party APIs. JavaScript, HTML, and CSS work together to display a complex page.

JavaScript is commonly used in browsers, and generally includes ECMAScript, DOM, and BOM. ECMAScript is the standard, DOM is the js API provided by the browser to operate html/css, and BOM is the js API provided by the browser to operate the browser's js API. If JavaScript is applied in nodejs, it is usually used for server-side programming, which can perform io operations, network operations, etc.

Features
Client-side code, executed on the client machine
1. The special thing about JavaScript is that it can also be executed as server-side code, but it needs Build a Node environment. node hello.js
2. Run on the browser
Interpreted language
is built into the browser or Nodejs platform js parser parses and executes, no need to compile before execution
Weakly typed language
Parse and execute sequentially from top to bottom

System environment

Linux operating system environment*

Windows

MacOS

editor

vi、vim*

vscode/sublime

Operating environment

Old: JavaScript cannot run independently + web page + console/fireBug

nodejs*

debug:

Firefox: firebug

console.log()/pop-up alert

2. js composition

1) ECMAScrpt [js standard] (100% compatibility) (similar to CoreJava, basic syntax is formulated)

Comments // , /**/

variable

Operator

flow control statement

array

object

function

regular expression

All js interpreters are compatible with ECMAScript

2) DOM: Document Object Model document object model

js API for operating html

Is an application programming interface for XML but extended for HTML. DOM maps the entire page into a multi-node structure.

var dom=document.getElementsByTagName(“input”);

var dom=document.getElementById(“input_name”);

dom.οnclick=function(){}

js language: basic syntax, basic library, extension library (jQuery DOM library)

3) BOM: Browser Object Model browser object model

js operating browser api

Developers can use the BOM to control parts of the page other than what is displayed by the browser. Pops up a new browser window; functions to move, zoom, and close the browser; navigator object that provides detailed information about the browser; location object that provides detailed information about the page loaded by the browser; screen object that provides detailed information about the resolution of the user's monitor; Support for cookies; support for XMLHttpRequest, ActiveXObject custom objects in IE

alert()/prompt()/confirm()

setInterval(),setTimeout()

XMLHttpRequest

Ajax

What needs to be noted here is that only ECMAScript is the standard, which means that it runs the same in most browsers and js parsers (node). However, DOM and BOM are APIs provided by major browser manufacturers themselves, and they are similar in use. , but there may also be some incompatibilities.

js interpreter:

1) Browser manufacturers: Firefox (js standard), IE (js), Google (js)

compatibility:

The three components of JavaScript are supported to varying degrees in the current five major browsers (IE, Firefox, Chrom, Safari, Opera). Among them, all browsers generally have good support for ECMAScript3, and the greater the support for ECMAScript, the better. Although browsers have implemented some well-known common features, other features vary from browser to browser.

2) nodejs [network programming (http module)/database operation (mysql)/IO file (file)]

http://nodejs.cnCan be installed on mainstream operating systems such as linux windows macos unix

Features: Can run on the client side, server side, interpreted language, weakly typed language, executed sequentially from top to bottom.

In nodejs, there is no compatibility problem, because there is no dom/bom in nodejs, so remember not to execute any dom and bom code in nodejs. Since there is no compatibility problem, nodejs can make full use of js advanced standards, ES6 The syntax generally works completely in nodejs.

js features
  1. interpreted language

js -> nodejs (js interpreter)

  1. weakly typed language

The data type of the variable depends on the data type of the value

var a ;

a = 2; // The data type of a is number

a = true; // The data type of a is boolean

  1. sequential interpretation execution
  2. It can be used as a front-end scripting language or a back-end language, depending on the application platform (browser/operating system) and the framework used (dom, jquery/http, mysql, file)
Using JavaScript in web pages

Internal JavaScript
Write the HTML, add the element in the <head> tag body, and then fill in the js code Just come in. <script>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript">
    alert('hello javascript')
  </script>
</head>
<body>
</body>
</html>
Using JavaScript in web pages

External JavaScript
Create a separate js file with the suffix .js, write the HTML file, and add it in the <head> tag body <script> element, use the src attribute of the script tag to import the js file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript" src="hello.js"></script>
</head>
<body>
</body>
</html>
The difference between using JavaScript in body and head

The JavaScript in the body section will be executed when the page is loaded, and the JavaScript in the head section will be executed when it is called.

​ Because the browser parses html from top to bottom. If JavaScript is placed in the head, it will be parsed first, but the body has not been parsed at this time, so a null value will be returned. Generally, a listener is bound and the code is executed after all the HTML documents have been parsed.

windows.onload = function(){
    
    
	// 这里放执行的代码
}

This means that if we want to define a global object, and this object is a button on the page, we must put it in the body. The reason is obvious: if we put it in the head, then when you define it, That button has not been loaded, and it may be an undefind. It is generally customary to place JavaScript at the end of the body, similar to last-child.

Writing JavaScript in vi/vim
console.log('hello JavaScript')

Just use the node command to execute it

$ node hello.js
Comment

Similar to most languages, JavaScript also requires comments to explain the meaning of its code, or for code debugging. The commented code will be ignored by the browser and will not be executed.
Single-line comment
// I am a comment
Multi-line comment
/*< /span> */ a comment
I am also

3. Keywords and reserved words

Keyword: (has special functions in js)

break do try typeof
case else new var
catch finally return void
continue for switch while
debugger this function with
default if throw instanceof
delete in

Reserved words: (may become keywords in the future)

abstract enum int short
boolean export interface static
byte extends long super
char final native synchronized
class float package throws
const goto private transient
debugger double implements protected
volatile import public

1) Case sensitive

typeof keyword, typeOf non-keyword

2) Identifier

Refers to the name of a variable, function, attribute or parameter of a function. An identifier is one or more characters combined according to the following rules:

1. Composed of letters, numbers, underscores, and $

2. Can only start with letters, underscores, and $.

3. Keywords cannot be used as identifiers. Naming uses camel case naming

  1. statement

Each statement ends with a semicolon. If the semicolon is omitted, the parser determines the end of the statement, that is, the semicolon can be omitted, but we require that there should be a semicolon at the end of each statement.

4.Variables

A variable is a container of values, and the value of the container can be changed at any time. ECMAScript variables are weakly typed (loosely typed) and can be used to store any type of data. Use the var keyword when defining variables.
Use of variables:
Declare var message;
Initialize message = “hello”
Declare and initialize var message = “hello”;
Define multiple variables var message= “hello”, found=false, age = 29;
Variable name Naming rules:
Variable names consist of letters, numbers, underscores and $.
Do not use underscores or numbers as the beginning of variable names.
Variable names should have a certain meaning and use the camel case naming rule var userAgeTotal = "";
Do not use keywords or reserved words

  • Use of variables
    The use of variables generally follows three steps: declaration, initialization and use
// 变量声明
var a ;
// 变量初始化
a = 3;
// 变量调用
console.log(a);
  • js is a weakly typed language

Weakly typed languages ​​have the following characteristics:

  1. The data type of the variable is determined during initialization
  2. The data type of a variable can change at any time
  3. Type breakdown is not obvious
  • Java is a strongly typed language
  1. The data type of a variable is determined when it is declared

  2. The data type of the variable must be determined and cannot be changed.

  • was

var is used to declare a variable. In es6, you can declare a variable through let and a constant through const.

    1. Variables can be declared repeatedly
var a = b = c = 3;
var d = 10,e = 20,f,g;
//弱类型语言,变量容器可以混合使用
var a = "hello world";//变量的重复赋值(相同的数据类型、不同的数据类型)  
function a(){
    
    }
  • Variable declarations are hoisted (as are function declarations)
//console.log(b);//报错
console.log(a);//不会报错
var a = 3;
//等价于:
var a;//在所有代码执行之前,js解释器会将js中所有的var声明的变量提升。
console.log(a);
a=3;
  • The scope of the variable declared by var

Case 1

function foo(){
    
    
  if(true){
    
    
    var a = 3;  
    console.log("inner",a);//inner 3
  }
  console.log("outer",a);//inner 3  //没有块级作用域
}
foo();
console.log(a);//error!  函数作用域:局部作用域
// var 的变量声明提前知会提升到当前作用域的最前面

Case 2

//如果在函数中定义变量没有加var,该变量为全局变量
function test(){
    
    
  message = "hello"; 
}
test();
console.log(message); //可以访问

Case 3

//全局作用域
function b() {
    
    
  a = 10;
  return;
}
var a = 1;
b();
console.log(a);//10

Case 4

x = 1;//window.x  global.x
console.log(x); //1
function y() {
    
    
  console.log(x); //undefined
  console.log(this.x);//1
  var x = 2;
  console.log(x); //2
}
y();
console.log(x);//1

Case 5

//函数作用域:局部作用域
var a = 1;
function b() {
    
    
  a = 10;
  return;
  //a函数声明,提前变量a,将a认为是函数b作用域的变量,具有局部效果
  function a(){
    
    }
} 
b(); 
console.log(a); // 1

5.Data type

JavaScript basic data types:

Value type (basic type): String, Number, Boolean, Null, Undefined, Symbol.

Reference data types: Object, Array, Function.

Note: Symbol is a new primitive data type introduced in ES6 to represent unique values.

JavaScript has dynamic typing

JavaScript has dynamic typing. This means that the same variable can be used as different types

var x;               // x 为 undefined
var x = 5;           // 现在 x 为数字
var x = "John";      // 现在 x 为字符串
String String

Strings are variables that store characters (such as "Bill Gates").

A string can be any text within quotes. You can use single or double quotes:

var carname="Volvo XC60";
var carname='Volvo XC60';

You can use quotes within a string, as long as they don't match the quotes surrounding the string:

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

You can use character literals to escape characters
\n line feed\t tab\b backspace
\r carriage return\ slash ' Single quotation mark
" Double quotation mark
The character length can be obtained through the length attribute

var str = "我是字符串";
console.log(str);
console.log(str.length);
var s4='\n\t\b\r';
Number Number

JavaScript has only one number type. There are many types of numbers. According to the numerical precision, they can be divided into integer (int), single precision (float), and double precision (double). According to the number representation method, they can be divided into binary (Binary), octal (Octal), and decimal system (decimal system). ), hexadecimal. But in js, all numbers are represented by Number.

display method

Integer:

​ Decimal 55 consists of 0~9

​ Octal 070, the first bit is 0, the other bits are composed of 0~7

​ Hexadecimal 0x11, the first bit is 0x, the other bits are 09, AF

var num1 = 34;         //不使用小数点来写
var num2 = 010;        //8
var num3 = 0x10;       //16
console.log(x1, x2, x3, x4);
Floating point number:

​ The so-called floating point value means that the value must contain a decimal point, and there must be at least one digit after the decimal point. The maximum precision of floating point values ​​is 17 decimal places

​ Ordinary floating point number 3.1415926

​ Scientific notation 3.125e7 is 31250000

var f1 = 3.1415926;  //3.1415926
var f2 = 3.125e7;    //31250000
console.log(f1, f2);
Non-numeric value:

​ This value represents a situation where an operand that was supposed to return a value did not return data.

var a = 10/ "a";	// a为NaN
Non-numeric detection:

​ Determine whether the parameter is "not a numerical value" and return true when the parameter para is not a numerical value.

isNaN(NaN);	// true
Value range:

Due to memory limitations, ECMAScript cannot save all values ​​in the world.

The smallest value that ECMAScript can represent is stored in Number.MIN_VALUE

The largest value that can be represented is stored in Number.MAX_VALUE.

​ If the result of a certain calculation exceeds the JavaScript numerical range, Infinity (positive infinity) or -Infinity (negative infinity) will be returned.

var a = 9/0;   // Infinity
Number.MIN_VALUE    5e-324
Number.MAX_VALUE   1.7976931348623157e+308
Numeric range detection:

​ Use the isFinite() function to determine whether the parameter is between the maximum value and the minimum value. If so, return true

var a = isFinite(9/0);	// false
Boolean

Boolean (logic) can only have two values: true or false.

var x=true;
var y=false;
Null

There is only one value of this type, which is null. null can represent a pointer to a null object.

var a = null;

If a variable is intended to hold an object in the future, you can initialize the variable to null and nothing else, so you can tell by checking for the null value.

Whether the corresponding variable already holds a reference to an object.

if(car !== null ){
    
      //car对象执行某些操作}
Undefined

Undefined This value indicates that the variable does not contain a value. undefined.

var a;
console.log(a,typeof a);//undefined 'undefined'
var a = undefined;
console.log(a,typeof a);//undefined 'undefined'
undefined and null relationship

undefined inherits null, so the result of undefined == null is true, but null means an empty object, and undefined means undefined;

Null has different uses than undefined. Null can be used to represent an empty object, but there is no need to explicitly set the value of a variable to undefined.

//null vs undefined
console.log(undefined == null); //true  //undefined派生自null
console.log(undefined === null);//false
if(null == undefined){
    
    console.log('相等的')}
if(null === undefined){
    
    console.log('完全相等')}
// ==, 等同  的意思, 两边值类型不同的时候,要先进行类型转换为同一类型后,再比较值是否相等。 
// ===,恒等  的意思, 不做类型转换,类型不同的结果一定不等。
// "=="表示只要值相等即可为真,而"==="则要求不仅值相等,而且也要求类型相同。
// 建议:尽量使用严格运算符 ===。因为"=="不严谨,可能会带来一些违反直觉的后果。

Reference data type

In addition to the above basic data types in js, all other types can be attributed to reference data types.

ObjectObject

Objects are objects that simulate real life. Objects are composed of key-value pairs. All key-value pairs are enclosed by curly braces.

var dog = {
    
    
	name: 'momo',
	age: 4
}

You can get the properties of an object using dot syntax

dog.name; //momo
dog.age;	//age
ArrayArray

An array is a special object that contains multiple values. Values ​​are separated by commas, and all values ​​are enclosed in square brackets.

var classArr = ['web2104','web2105','web2106']
var studentArr = ['zhangsan','lisi','wangwu']

Corresponding data can be obtained through array subscripts

classArr[0]; // web2104
Function

Functions are code execution units used to implement certain special functions.

function sum(a, b) {
    
    
  return a + b;
}
//执行函数
sum(1,2); // 3
How basic data types and reference data types are stored in memory
  • Basic data types

Basic data type variables are maintained in the stack area, and the values ​​of basic data types are stored in the stack area.

For example:

var a = 123;
b = a;
a = 456;

1.var a = 123; b = a; the basic data type is stored in the stack memory, as shown in the figure below, when b = a, b directly stores the value of a in it

2.a = 456; will change the value of a to 456, but has no effect on b, so the final output will be a = 456;b = 123;

Conclusion:The values ​​of basic data types exist on the stack, and values ​​exist independently. Modifying one value will not affect other variables
  • Reference data type

The reference address of the reference data type is stored in the stack area, and the value is stored in the heap area.

For example:

var obj = {
    
    
  name: 'zhangsan'
}
var obj1 = obj; //将对象obj赋值给对象obj1
console.log(obj.name);  //zhangsan
console.log(obj1.name); //zhangsan

// 修改obj的name
// 当obj属性name变为"lisi"时,obj1属性name也变为"lisi"
obj.name = 'lisi';
console.log(obj.name);  //lisi
console.log(obj1.name); //lisi
Conclusion:When the reference type is stored on the stack, the value is the address of the object. obj and obj1 point to the same address, so when the name value of obj changes to "lisi", obj1 will also change
  • Deep copy and shallow copy

Mainly for reference data type parameters, shallow copy means copying only the reference address, and deep copy means cloning the object.

How to implement deep copy
  • Implement deep copy through json object (JSON.stringify, JSON.parse)
  • Object.assign()copy
  • Lodash function library implements deep copy
  • Implement deep copy recursively
  • etc.

6. Type judgment

In actual development, we often have to determine the data type of a variable.

  • typeof

Use typeof to determine the data type
Return the type of data pointed to by the variable name
Syntax: typeof variable name
The return value is as follows:
“undefined” undefined
“boolean” Boolean type
“string” string
“number” value
“object” object or null or array
“function” function

Typeof can be used to determine the type of a variable

var a = 3;
typeof a;  // number
if((typeof a) == "string"){
    
    }
if(a == "null"){
    
    }
if(a == null){
    
    }
  • isNaN

Determine whether it is not a number

var a = 10/'a';
isNaN(a);    //true
  • isFinite

Determine whether it is a valid value

var a = 10/0 ;
isFinite(a)   // false

Guess you like

Origin blog.csdn.net/qq_52342759/article/details/134126098