JavaScript | Basic syntax (writing form, data types, arrays, functions, objects)

Link

1. First introduction to JavaScript

JavaScript (JS for short)
is one of the most popular programming languages ​​in the world.
It is a scripting language that runs through an interpreter.

Although js is mainly used for the development of front-end pages , in fact, it can also be used for server development/client program development .

JavaScript was originally used to complete simple form validation (verify data legality), but later accidentally became popular.
Currently, JavaScript has become a universal programming language.

What JavaScript can do:

  • Web development (more complex special effects and user interaction)
  • Web game development
  • Server development (node.js)
  • Desktop program development (this is where Electron and VSCode come from)
  • Mobile app development

Brendan Eich, the father of JavaScript

Former Brandon:

Insert image description here

Brandon after inventing JavaScript:

Insert image description here

In 1995, it took 10 days to complete the design of JS (because the design time was too short and some details of the language were not considered rigorously enough, resulting in a chaotic program written in Javascript for a long time). Initially at Netscape, it was
named LiveScript,
it is generally believed that the reason why Netscape named LiveScript JavaScript at that time was because Java was the most popular
programming language at the time, and the name "Java" helped the spread of this new language.
In fact, the syntax styles between Java and JavaScript are very different.

For the history of JavaScript development, you can refer to Ruan Yifeng’s blog
http://www.ruanyifeng.com/blog/2011/06/birth_of_javascript.html

JavaScrip:

  • HTML: The structure (bone) of a web page
  • CSS: Web page performance (hide)
  • JavaScript: The behavior (soul) of the web page

Front-end development JS is the only one

Challenger:

  1. Dart (made by Google, a programming language that comes with the next-generation mobile development platform)
  2. Web Assembly.Similar to "assembly language", a set of basic instructions is defined on the browser, and other mainstream programming languages ​​can be converted into WebAssembly through some third-party tools. At this time, C++, Java, Python... can all realize page development through this method...
  3. TypeScript [the most promising challenger] is also a general that is making very rapid progress. The
    relationship between JS and TS is similar to the relationship between C and C++. "Compatible"
    TS fully supports the current syntax of JS and introduces some new ones. The grammatical rules allow programmers to write more comfortably. The attraction of TS is still very big for the existing front-end development programmers [poaching]. However, despite this,
    TS has not completely replaced JS. In the front-end circle, JS is still the main tool

JavaScript running process:

  • The code written is saved in a file , that is, stored on the hard disk (external memory)
  • Double-click .htmlthe file browser (application) to read the file and load the file content into memory (data flow direction: hard disk => memory)
  • The browser will parse the code written by the user and translate the code into binary instructions that can be recognized by the computer (the job of the interpreter)
  • The obtained binary instructions will be loaded and executed by the CPU (data flow direction: memory => CPU)

The browser is divided into rendering engine + JS engine:

  • Rendering engine: parses html + CSS, commonly known as "kernel"
  • JS engine: that is, the JS interpreter, typically the V8 built into Chrome
  • The JS engine reads the JS code content line by line, then parses it into binary instructions, and then executes

Node.js:

With JS, the web page you see is actually equivalent to a web app (no different from an ordinary client program).
JS is similar to the previous HTML/CSS, both run on the browser and
browse The browser has a built-in JS execution engine (the so-called engine refers to our JVM).
Among them, the chrome browser has a built-in JS engine, which is also developed by Google itself. It is a very well-known engine called V8the engine
and it has a large Dude, take this V8 engine out of the browser, repackage it, and it becomes Node.js

JS is a programming language
. To execute JS, you need a JS execution engine
Node.js. This is a JS running platform (targeted at the browser).
The browser runs on the client , and Node.js can run on the client. It can also be run on the server (separate execution program), which can give JS the ability of client development/server development.

vue.js is just a library/framework based on JS that runs on the browser.

JavaScript consists of:

For JS executed on the browser, it can be considered to be divided into three parts

  • ECMAScript (ES for short): JavaScript syntax
  • DOM API : A set of APIs provided by the browser to operate page elements . The page document object model operates on the elements in the page.
  • BOM API : Browser Object Model, a set of APIs provided by the browser to operate the browser window

For JS executed on Node.js, it is divided into two parts:

  1. JS core syntax
  2. The API provided by Node js (this API has nothing to do with DOM / BOM) provides some other things, such as file operations, network operations, system-level operations...

With JS syntax alone, you can only write some basic logical processes

But if you want to complete more complex tasks and interact with browsers and pages, you need DOM API and BOM API. This
mainly refers to JS running on the browser side. If it is JS running on the server side, you need to use node. js API,
you don’t need to pay attention to DOM and BOM.

Important concept: ECMAScript
is a set of "standards". No matter what kind of JS engine it is, it must comply with this standard to implement it.
What is a standard? Cars work on the same track, books work on the same text. One of Qin Shihuang's greatest contributions is to develop a set of standards.
Third-rate companies make products, first-rate companies make standards


2. The first program

1、script

  • JS running in the browser is inseparable from html, and usually needs to be embedded into html for writing.

  • Many programming languages ​​can be placed in script, but now JS is the default option.

  • What follows the statement in JS ;is not necessary. You may or may not write it, but it is recommended to write it.

  • Note : String constants in JS can be represented by single quotes or double quotes . It is recommended to use double quotes in HTML and single quotes in JS.

<script>
	alert('hello');
</script>

Insert image description here


2. JavaScript writing form

Embedded:

Write JS into script tag

<button onclick="alert('hello')">这是一个按钮</button>

Inline:

Write JS inside HTML elements

External expression:

Write JS into a separate .js file and introduce it through script in HTML

alert('hello app.js');
<script src="app.js"></script>

Insert image description here

Note : In this case, no code can be written in the middle of the script tag, it must be empty (the code will not be executed even if it is written), which is suitable for situations with a lot of code.

<script src="app.js">
    alert('hello');
</script>

In this way, there will only be one pop-up window, and there will be no internal hello. It needs to be written separately.


3. Comments

  • JS comments: //, multi-line comments /* */ cannot be nested

  • Notes on CSS:/**/

  • HTML comments:<!---->


4. Input and output

There are actually many ways for JS to interact with users

Input: prompt
pops up an input box

alert pop-up box, bad experience

// 弹出一个输入框
prompt("请输入您的姓名:");

Output: alert
pops up a warning dialog box and outputs the result

// 弹出一个输出框
alert("hello");

Output: console.log
prints a log on the console (for programmers to see) – logs are an important means for programmers to debug programs

Important concept:
console is an "object" in js
. It means taking a certain attribute or method in the object. It can be intuitively understood as "the"
console.log can be understood as: Use the "console" object's "log" method

// 向控制台输出日志
console.log("这是一条日志");

In development, the most commonly used output method will output the log to the console,
not the system's black box, but the browser's own console (can be seen in the developer tools), (F12) => Console tab page to see the results

If there are some syntax errors or runtime errors in the js code, they will also be displayed in the console: no definition, line 13

Insert image description here


3. JavaScript basic syntax

1. Type

1.1. Variables

Define variables:

var variable name = initial value;

<script>
    var num = 10; // 数字类型的变量
    var s = 'hello';
    var arr = []; // 数组类型的变量       
</script>

No matter what type of variable, varthis keyword is used to represent it uniformly. As for the specific type of the variable, it depends on the initialized value and what type it is.

JS does not distinguish between integers and floating point types

It does not need to be initialized . When not initialized, the value of the variable is a special value: ``undefined`, but you cannot create an uninitialized value and specify that it is a string type...

In fact, this style of writing is more mainstream (more programming languages ​​are set this way), including languages ​​like C++ and Go, which also support similar writing methods mentioned above.

Dynamic type:

When modifying variables, there is a small problem:
if a is originally a numeric type, when assigning a value, you can assign it a numeric type, a string type, or any type . At this time, the type of variable a also changes accordingly.

<script>
    var a = 10;
    a = 'hello'
    console.log(a);       
</script>

The type of a variable can change with assignment during runtime. This behavior is called "dynamic typing" (runtime)
Python, PHP, Ruby...

Languages ​​like Java do not support such runtime type changes. This behavior is called "static typing"
C, C++, Java, Go, Rust…

Python has developed some signs of "surrending to the enemy"
a = 10
a:int = 10

Looking at it from the perspective of 2022, the static type camp has a complete victory!!!
Now the industry has basically reached a consensus: it is believed that static types are better than dynamic types. With
static types, the compiler can do more checks, so that some errors can be discovered in advance. Now, the development tool (IDE) can also do more analysis based on types and provide richer support.

Dynamic typing also has its own benefits. By writing a function, you can support multiple different type parameters at the same time (no need for "overloading" / "generic" syntax at all). However, despite this advantage, overall, it still has disadvantages
. More than profitable

let:

Nowadays, we tend to use let instead of var.
Var is an old version (early design). In many places, it is actually counterintuitive. Indeed, let is more intuitive than var.

<script>
	{
    
    
        var num = 10;
        let num2 = 10;
	}
	console.log(num); // 运行没有问题
    console.log(num2);
</script>

1.2. Basic data types

Several types built into JS:

  • number: Number. Does not distinguish between integers and decimals .
  • boolean: true, false.
  • string: string type.
  • undefined: There is only the unique value undefined. Indicates an undefined value.
  • null: Only the only value null. Represents a null value

When using binary numbers in daily life, octal and hexadecimal are often used to represent binary numbers.

var a = 07; // 八进制整数, 以 0 开头
var b = 0xa; // 十六进制整数, 以 0x 开头
var c = 0b10; // 二进制整数, 以 0b 开头

Special numeric values:

  • Infinity: Infinity, larger than any number. It means that the number has exceeded the range that JS can represent.
  • Infinity: Negative infinity, smaller than any number. It means that the number has exceeded the range that JS can represent.
  • NaN: Indicates that the current result is not a number. Not a number

Notice:

  1. Negative infinity and infinitesimal are not the same thing. Infinite means infinitely close to 0, and the value is 1 / Infinity

  2. 'hehe' + 10 will not get NaN, but 'hehe10', which will implicitly convert the number into a string and then concatenate the strings.

  3. You can use the isNaN function to determine whether it is a non-number

var max = Number.MAX_VALUE;
// 得到 Infinity
console.log(max * 2);
// 得到 -Infinity
console.log(-max * 2);

// 如果运算结果,得到的不是数字的值,就会出现 NaN
console.log('hehe' - 10);

// 和 Java 类似,如果把字符串和数字相加,那么就会得到一个 "字符串拼接" 的效果
console.log('hello' + 10);

console.log(isNaN(10)); // false
console.log(isNaN('hehe' - 10)); // true

1.3. string string type

  • Both single and double quotes are acceptable

  • If the string itself contains quotation marks , at this time, you can flexibly match single and double quotation marks to avoid using escape characters.

console.log('my name is "zhangsan"'); // my name is "zhangsan"

Find the length:

Just use the length property of String. The length here, the unit is "character"

let s = 'hello world';
console.log(s.length); // 11
s = '你好';
console.log(s.length); // 2

String concatenation:

Note that you must make sure whether the added variables are strings or numbers.

console.log(100 + 100); // 200
console.log('100' + 100); // 100100

1.4. boolean Boolean type

The Boolean type in JS will be treated as 1 and 0 (Boolean in Java is Boolean and will never be confused with numbers)

let a = true;
console.log(1 + a); // 2

I think this setting method is actually unscientific!! "Implicit type conversion"

If a programming language supports implicit type conversion, the type is considered to be weaker (C, JS, and PHP are considered weakly typed programming languages).
If a programming language does not support implicit type conversion, the type is considered to be stronger (Java, Go, Python is considered a strongly typed programming language)

Strong typing means that the differences between types are greater and the boundaries are clearer
. Weak typing means that the differences between types are not big and the boundaries are more blurred.

Static typing/dynamic typing vs strong typing/weak typing are unrelated concepts (orthogonal)

Insert image description here


1.5. undefined undefined data type

  • The type undefined has only one value: undefined

  • If a variable has not been initialized, the result is undefined , which is of type undefined

let num;
console.log(num); // undefined

Undefined situation (illegal situation)
In the future, JS may be set to directly compile and report errors without initializing variables.
However, the current JS requirements are not so strict, so a special value like undefined is created to represent this. illegal situation

In actual development, you should not actively use undefined, nor should you rely on undefined.

let num2 = null;
console.log(num2); // null

null means that the current value is "no value". This concept
is legal.
In actual development, using null is completely ok.


2. Operator

2.1. Arithmetic operators

Division /, in JS, does not distinguish between integers and decimals, both are numbers

console.log(1 / 2); // 0.5

Most programming languages ​​- 1/2 => 0
but a few exceptions: JS, Python3 (Python2 is not) - Dart result is 0.5


2.2. Comparison operators

There are two styles of comparison equality in JS:

== !=(Implicit type conversion will be performed): Only the values ​​of the two variables are compared , but the types of the two variables are not compared. If the two variables can be converted into the same value through implicit type conversion, they are considered equal at this time. of

= !(Implicit type conversion will not be performed): Both the value of the variable and the type must be compared. If the types are not the same, they are directly considered to be unequal.

let a = 10;
let b = '10';
console.log(a == b); // true
console.log(a === b); // false

When it comes to comparing two objects, there are three dimensions of comparison:

  1. Compare identities (whether they are the same object)
  2. Comparison value (whether the data stored in the object is the same)
  3. Compare types (whether two objects are the same type)

Java == comparison identity
equals can be overridden. If not overridden, the default is to compare identities. By overriding, it can be set to the comparison value instanceof comparison type.


3. Logic and logical or

&& || is very different from Java.
The behavior of && and || in Java is very simple, that is, it returns a true or false.
&& and || in JS return one of the expressions.

  • c = a || b
    If the value of a is true (not 0), the value of c at this time is the value of the expression a.
    If the value of a is false (is 0), the value of c at this time is the expression The value of formula b

  • C = a && b
    If the value of a is false, the value of c at this time is the value of expression a.
    If the value of a is true, the value of c at this time is the value of expression b.

Derived from an idiom in JS, determine whether a variable is a "null value", and if it is a null value, assign a default value


4. Conditional statements

Case : Determine whether a number is odd or even

let num = 10;
if (num % 2 == 0) {
    
    
    console.log('num 是偶数');
} else {
    
    
    console.log('num 是奇数');
}

Note! It cannot be written as num % 2 == 1, it is an odd number, and the result of a negative odd number % 2 may be -1


5. Array

5.1. Creation of array

This way of writing is more like creating an object in Java (rarely used)

let arr = new Array();

Create using literal method [commonly used]

let arr = [];
let arr2 = [1, 2, 3];

This is very different from Java. When Java defines an array here, the int[] type is used. Java uses {} for array initialization
while JS uses [].

Note : JS arrays do not require elements to be of the same type . This is very different from statically typed languages ​​such as C, C++, and Java, but the same is true for dynamically typed languages ​​such as Python and PHP.

In Java, int[] is an integer array and String[] is a string array. In JS, there is only one kind of array, which is called an array

let arr = [10, 'hello', true, undefined, null, []];

5.2. Print array:

In JS, you can print the array contents directly through console.log

let arr = [10, 'hello', true, undefined, null, []];
console.log(arr);

5.3. Get array elements

Get elements by subscript: subscripts are also calculated from 0

Notice:

1. According to previous understanding, Java requires array subscripts to be in the range of 0 -> length - 1. If it exceeds the range, an exception will be thrown in JS. This is not the case. When we access a
subscript that exceeds the range, we get The result is undefined and no exception will occur.

let arr = [1, 2, 3];
arr[100] = 10;
console.log(arr);

Insert image description here

The length becomes 101, and then the content of the array, the first three elements are still 1, 2, 3, the element with the subscript 100 is 10, but the empty attribute in the middle * 96, which means that these middle elements are still undefined

2、arr[-1] = 10;

Insert image description here

At this time -1 is not so much a subscript as an "attribute" and does not affect the length of the array.

3、arr[‘hello’] = 10;

Insert image description here

  • The array in JS is not a serious array!!!
  • In addition to being able to handle array work, it can also handle map work (representing key-value pairs) => Here it is said that an array is a map, or more accurately, it is an "object"
  • In JS, you can add attributes to objects at runtime.
  • arr['hello'] is adding a new attribute to the arr object. The name of the attribute is hello and the value of the attribute is 10.
let arr = [1, 2, 3];
arr.hello = 30;
console.log(arr);
console.log(arr['hello']); // 1
console.log(arr.hello); // 2

Insert image description here

These syntaxes are not unique to JS. All dynamically typed languages ​​are set up in this way. (PHP is set up in almost the same way as JS, but Python is slightly different, but the essence remains the same.) The above codes are all "static
" "Type" vs "Dynamic Type" The collision between two schools


5.4. Get the array length

  • .lengthYou can get it through
  • In JS, the length attribute can be changed
let arr = [1, 2, 3];
arr.length = 5;
console.log(arr.length);
console.log(arr);

Running result: 5
test.html:32 (5) [1, 2, 3, empty × 2]


5.5. Add elements to the array

The most common insertion operation: push method , which can append an element to the end of the array (add operation in Java ArrayList)

let arr = [];
for (let i = 0; i < 10; i++) {
    
    
    arr.push(i);
}
console.log(arr);

5.6. Delete elements in the array

spliceThis method replaces a certain interval in the array and can be used to delete or insert elements .

let arr = [1, 2, 3, 4, 5, 6];
arr.splice(2, 3); // 从下标为 2 的位置,删除 3 个元素
console.log(arr); // [1, 2, 6]
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
console.log(fruits); // ['Banana', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Mango']

6. Function

6.1. Grammar format

Function, method, the same thing, different vests

Normally, the difference between these two concepts is not considered, but if it must be considered, it can be understood like this:

  • Function : It is a piece of code that is independent of the "object"
  • Method : It is a code fragment that relies on an object . Method => member function.
    In Java, since such code fragments are dependent on classes and objects, they are all "methods" in Java.

For the function parameter list in JS, it is not necessary to write the formal parameter type or the return value type.

// 创建函数/函数声明/函数定义
function 函数名(形参列表) {
    
    
	函数体
	return 返回值;
}
// 函数调用
函数名(实参列表) // 不考虑返回值
返回值 = 函数名(实参列表) // 考虑返回值

The function definition does not execute the function body content. It must be called before it is executed. It will be executed several times after it is called.

function hello() {
    
    
console.log("hello");
}
// 如果不调用函数, 则没有执行打印语句
hello();

6.2. About the number of parameters

The number of actual parameters and formal parameters does not need to match , but actual development generally requires that the number of formal parameters and actual parameters match.

function add(x, y) {
    
    
    return x + y;
}

let result = add(10, 20);
console.log(result); // 30

result = add('hello', 'world');
console.log(result); // helloworld

result = add('hello', 10);
console.log(result); // hello10
  • When specifying parameters for a function, there is no need to write parameter types. The type of actual parameters passed in can be arbitrary , as long as it can support the internal logic of the function (for example, two parameters are required to be added here)
  • Because of this feature, JS naturally does not need syntax such as "generics" / "overloading"

Generally, when writing code, the actual parameters passed in when calling are required, and the number matches the formal parameters. But in fact, JS does not impose such restrictions on grammar.
If the number of actual parameters and formal parameters is different, it is not impossible!!!
Like the add method above, if you want to add an arbitrary number of numbers, , in fact, there is no need to write multiple versions of code

Can support the addition of up to 7 parameters:

function add(a, b, c, d, e, f, g) {
    
    
    return a + b + c + d + e + f + g;
}

console.log(add(10, 20)); // NaN
console.log(add(10, 20, 30)); // NaN
console.log(add(1, 2, 3, 4, 5, 6, 7)); // 28

Formal parameters that are not passed as parameters are undefined.

If you want your code to support both the addition of numbers and the addition of strings, it is essential to determine whether the
first parameter is a string or a number (JS, typeof). Through the first The type of a parameter determines the default value of subsequent parameters, whether it is 0 or "".
If there are more actual parameters than formal parameters, the extra actual parameters are equivalent to disappearing (you cannot get them inside the function).
The parameters here The operation of variable number is not a common attribute of "dynamic type", but a proprietary attribute of JS.
The purpose of doing this is to make the code more "flexible", but in most cases, "flexible" has a derogatory connotation. word


6.3. Function expression

In JS, a function is a "first-class citizen" function. Just like an ordinary variable , it can be assigned to other variables, can be used as a parameter of another function, and can also be used as the return value of another function... (Function There is no essential difference from ordinary variables, but variables such as functions have one more function than ordinary variables: callable). The so-called function expression is actually assigning a function to a variable.

function hello() {
    
    
    console.log('hello');
}
let f = hello;

hello is a function name, and there is no () after hello, indicating that this operation is not a function call, but just a simple function assignment.
f is a variable of function type.

console.log(typeof(hello)); // function
console.log(typeof hello); // function

The above hello function can also be called through f:

function hello() {
    
    
    console.log('hello');
}
let f = hello;
f(); // hello

The two operations can be combined into one operation, which not only defines the hello function, but also assigns hello to f

let f = function() {
    
    
    console.log('hello');
}

Going one step further, you can omit hello. At this time, you completely rely on f to find the function.

let f = function() {
    
    
    console.log('hello');
}

Define a function without a name and assign this function to the variable f. You can later call this function based on f.

Functions without names, also known as "anonymous functions", have another name: lambda expressions


7. Scope

The valid scope of an identifier name in the code. Before the ES6 standard, the scope was mainly divided into two:

  • Global scope : takes effect in the entire script tag or a separate js file
  • Local scope/function scope : takes effect inside the function

ES6:
ES6 is actually the version of JS. JS was formerly known as ECMAScript, and can also be referred to as ES. The versions of JS are the latest versions of JS
represented by ES numbers . It is also more than ten years after ES. The status of ES6 is equivalent to Java 8 in
status in java

Similar versions of Java: Java 8. => Java 18

Before ES6, there was no block-level scope
. After ES6, let was introduced, and there was block-level scope. A variable defined inside {} cannot be accessed by {}
. Note: In JS, the code inside {} can access variables outside {}

let num = 10;

function hello() {
    
    
    console.log(num); // 10
}

hello(); // 10
let num = 10;

function hello2() {
    
    
    function hello() {
    
    
        console.log(num);
    }

    hello(); // 10
}

hello2();

The scope in JS supports "level-up" search.

Scope chain : Internal functions can access the variables of external functions, using a chain search method, searching from inside to outside.

Currently in the hello function, I try to print num, but there is no num variable in hello.
So I searched higher up and found hello2, but there was no num in hello2, so I
continued to search higher and found the global scope. If num is found,
if the last global scope is not found, an error will be reported——

What if there are multiple variables with the same name on different nodes of the scope chain?
Search from the inside out, whoever you find first will be the winner

let num = 10;

function hello2() {
    
    
    let num = 20;
    function hello() {
    
    
        console.log(num);
    }

    hello(); // 20
}

hello2();

Implement binary search based on JS

	function binarySearch(arr, key) {
    
    
            let left = 0;
            let right = arr.length - 1;
            while (left <= right) {
    
    
                // JS 除法 向上取整
                let mid =  Math.ceil((left + right) / 2);
                if (arr[mid] > key) {
    
    
                    right = mid - 1;
                } else if (arr[mid] < key) {
    
    
                    left = mid + 1;
                } else {
    
    
                    return mid;
                }
            }
            return -1;
        }

        let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let key = 3;
        let ans = binarySearch(arr, key);
        if (ans != -1) {
    
    
            console.log(key + ' 的下标是:' + ans); // 3 的下标是:2
        } else {
    
    
            throw new Error('没有此数');
        }
    </script>

Bubble Sort

	<script>
        function bubbleSort(nums) {
    
    
            for (let i = 0; i < nums.length - 1; i++) {
    
    
                let flg = true;
                for (let j = 0; j < nums.length - 1 - i; j++) {
    
    
                    if (nums[j] > nums[j + 1]) {
    
    
                        let tmp = nums[j];
                        nums[j] = nums[j + 1];
                        nums[j + 1] = tmp;
                        flg = false;
                    }
                }
                if (flg) {
    
    
                    break;
                }
            }
        }

        let nums = [2, 3, 15, 11, 21 ,7, 1];
        bubbleSort(nums);
        console.log(nums);
    </script>

Quick sort

<script>
	function quickSort(array) {
    
    
            quick(array, 0, array.length - 1);
        }

        function quick(array, left, right) {
    
    
            if (left >= right) {
    
    
                return;
            }
            let pivot = partition(array, left, right);
            quick(array, left, pivot - 1);
            quick(array, pivot + 1, right);
        }

        function partition(array, left, right) {
    
    
            let tmp = array[left];
            while (left < right) {
    
    
                while (left < right && array[right] >= tmp) {
    
    
                    right--;
                }
                array[left] = array[right];
                while (left < right && array[left] <= tmp) {
    
    
                    left++;
                }
                array[right] = array[left];
            }
            array[left] = tmp; // left right 相遇 就是基准
            return left;
        }

        let array = [2, 3, 15, 11, 21, 7, 1];
        quickSort(array);
        console.log(array);
</script>

4. Object

1. Use literals to create objects [commonly used]

  • An object is a collection of properties and methods
  • In Java, an object needs to have a class first, and then the object is generated based on the instantiation of the class.
    In Java, a class can be regarded as a custom type (two different types: Cat class and Dog class)
  • In JS, objects are not dependent on classes. All objects in JS are of type .object

In JS, objects can be created directly through {}:

let a = {
    
    }; // 创建了一个空的对象

let student = {
    
    
    name: '张三',
    age: 20,
    height: 180,
    weight: 120,

     sing: function() {
    
    
         console.log('sing()');
     },

     jump: function() {
    
    
         console.log('jump()');
     }
}
  • Use { } to create objects
  • Properties and methods are organized using key-value pairs
  • Use split between key-value pairs ,. The one after the last attribute is optional.
  • :Use split between keys and values
  • The value of the method is an anonymous function

Later, you can access it according to the student.property name method.

// 1. 使用 . 成员访问运算符来访问属性 `.` 可以理解成 "的"
console.log(student.name);
// 2. 使用 [ ] 访问属性, 此时属性需要加上引号
console.log(student['height']);
// 3. 调用方法, 别忘记加上 ()
student.sayHello();

2. Use new Object to create an object

Note that objects created using {} can also use student.name = "...";this method to add new attributes at any time.

var student = new Object(); // 和创建数组类似

// JS 中一个对象中有哪些成员,也都是动态可以改变的
student.name = "zhangsan";
student.height = 175;
student['weight'] = 170;
student.sayHello = function () {
    
    
	console.log("hello");
}

console.log(student.name);
console.log(student['weight']);
student.sayHello();

3. Create objects using constructors

The previous method of creating objects can only create one object, but using the constructor can easily create multiple objects.
For example: Create several cat objects.

var mimi = {
    
    
	name: "咪咪",
	type: "中华田园喵",
	miao: function () {
    
    
		console.log("喵");
	}
};

var xiaohei = {
    
    
	name: "小黑",
	type: "波斯喵",
	miao: function () {
    
    
		console.log("猫呜");
	}
}

var ciqiu = {
    
    
	name: "刺球",
	type: "金渐层",
	miao: function () {
    
    
		console.log("咕噜噜");
	}
}

It is more troublesome to write at this time. Using the constructor can extract the creation of the same properties and methods, simplifying the development process.

Basic syntax:

The constructor we are currently talking about is actually a special function that creates a group of similar objects in batches.

function 构造函数名(形参) {
    
    
	this.属性 =;
	this.方法 = function...
}

var obj = new 构造函数名(实参);

When you look inside the function and create attributes through this., the function is most likely a constructor.

The name after new is the name of the constructor, not the name of the "class"

Notice:

  • Use the this keyword inside the constructor to indicate the object currently being constructed
  • The first letter of the function name of the constructor is usually capitalized.
  • The function name of the constructor can be a noun
  • Constructor does not need to return
  • You must use the new keyword when creating an object

Use the constructor to recreate the cat object:

function Cat(name, type, sound) {
    
    
	this.name = name;
	this.type = type;
	this.miao = function () {
    
    
		console.log(sound); // 别忘了作用域的链式访问规则
	}
}

var mimi = new Cat('咪咪', '中华田园喵', '喵');
var xiaohei = new Cat('小黑', '波斯喵', '猫呜');
var ciqiu = new Cat('刺球', '金渐层', '咕噜噜');

console.log(mimi);
mimi.miao();

4. The difference between JavaScript objects and Java objects

In fact, JS itself feels that the latter two ways of creating objects in JS are quite awkward. The first way of writing is mainly used.
JS does not have the concept of class, which is applicable before ES6. After
ES6, the class keyword was also introduced, which allows the definition of objects. , is closer to Java, but this method is still not as simple as the first method
, and the first method of writing object definitions later became popular and went out of the circle. It is not only used by JS, but also by various other languages. In all scenarios, .JSON (data organization format) will be used.

Therefore, there are some ready-made objects in JS,
such as arrays, which can essentially be regarded as an object
. Although JS has objects, is JS considered an object-oriented programming language? We generally think that it doesn’t count!!
There are no encapsulation, inheritance, polymorphism, and other typical object-oriented features in JS

There is no native inheritance mechanism in JS,
but there is a way to save the country in a curve: "prototype". Based on the prototype mechanism, you can simulate an effect similar to inheritance: all the properties of an object are automatically added to In a new object...


Guess you like

Origin blog.csdn.net/qq_56884023/article/details/124869177