当前位置:网站首页>Js3day (array operation, JS bubble sort, function, debug window, scope and scope chain, anonymous function, object, Math object)
Js3day (array operation, JS bubble sort, function, debug window, scope and scope chain, anonymous function, object, Math object)
2022-07-02 12:44:00 【By the Difeng River】
List of articles
Array operation

The addition of array elements
Array .push() Method Add one or more elements to the end of the array , and Returns the new length of the array
// Filter array push
let arr1 = [2, 23, 124, 56, 78, 9, 7, 6, 5, 4, 3]
let new_arr = []
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] < 10) {
new_arr.push(arr1[i]) //push This sentence has a return value , Returns the length of the current new array
}
}
alert(`${
new_arr}`)

arr.unshift( What's new ) Method to add one or more elements to the of the array start , and Returns the new length of the array
// Filter array unshift
let arr1 = [2, 23, 124, 56, 78, 9, 7, 6, 5, 4, 3]
arr1.unshift(0, 1)
alert(arr1) // 0,1,2,23,124,56,78,9,7,6,5,4,3
Deletion of array elements
Array . pop() Method from the array Delete the last element , and Returns the value of the element
let arr1 = [1, 2, 3, 4, 5]
arr1.pop()
alert(arr1) // 1,2,3,4
Array . shift() Method from the array Delete first element , and Returns the value of the element
let arr1 = [1, 2, 3, 4, 5]
arr1.shift()
alert(arr1) // 2,3,4,5
Array . splice() Method Delete the specified number of elements , Returns an array of deleted elements 
let arr1 = [1, 2, 3, 4, 5]
arr1.splice(2, 1)
alert(arr1) //1,2,4,5
let arr1 = [1, 2, 3, 4, 5]
arr1.splice(2) // Delete by default start Position and all elements after it
alert(arr1) //1,2
Bubble sort
<script>
// Filter array unshift
let arr1 = [5, 23, 32, 5, 6, 1, 2]
for (let i = 0; i < arr1.length - 1; i++) {
for (let j = 0; j < arr1.length - i + 1; j++) {
let k = j + 1
if (arr1[j] < arr1[k]) {
let temp = arr1[k]
arr1[k] = arr1[j]
arr1[j] = temp
}
}
}
alert(arr1) //32,23,6,5,5,2,1
</script>
function
Return multiple values
<script>
function getSMax(arr) {
let max = arr[0], min = arr[0]
for (let i = 0; i < arr.length; i++) {
// if (max < arr[i]) {
// max = arr[i]
// }
// if (min > arr[i]) {
// min = arr[i]
// }
max = max < arr[i] ? arr[i] : max
min = min > arr[i] ? arr[i] : min
}
return [max, min]
}
let total = getSMax([42, 23, 5, 7, 676, 32, 4, 1])
alert(total)
</script>
argument Pseudo array
function fn() {
console.log(arguments)
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
alert(sum)
}
fn(1, 2, 34) //alert(37)
It can be seen that , The number of arguments is greater than the formal parameter , Yes, it can run , The number of arguments is less than the formal parameter return NaN.
It can also be like python Also set a default argument
function fn(x = 0, y = 1) {
// The default parameter is x=0,y=1
alert(x + y)
}
fn(3, 5) //8
fn() //1
debugging

Scope
Global scope Local scope The block level scope corresponds to the following corresponding variables 
Be careful ( I forgot today ):
If inside a function or block level scope , Variable No statement , Direct assignment , Also be Global variables see , But strongly not recommended
But there's a situation , The formal parameters inside a function can be regarded as local variables .
Scope chain
take Nearby principle To find the final value of the variable
function f1() {
let num = 123
function f2() {
console.log(num)
}
f2()
}
let num = 456
f1() // Console output 123
Anonymous functions

Immediate execution function
Scenario introduction : avoid Global variables Pollution between
grammar :
(function () {
alert(` Show me directly `) } ) ()
(function () {
alert(` Show you directly `) } () )
The essence : In fact, through the back () Already called
Be careful : Multiple immediate execution functions need to use ; separate , Otherwise, it will report a mistake ( No addition and no error report ~~)
Time conversion example
<script>
let time = prompt(" Enter the total number of seconds ")
function getTime(time) {
let h = parseInt(time / 60 / 60 % 24)
let m = parseInt(time / 60 % 60)
let s = parseInt(time % 60)
h = h < 10 ? '0' + h : h
m = m < 10 ? '0' + m : m
s = s < 10 ? '0' + s : s
document.write(`${
h} Hours ${
m} minute ${
s} second `)
}
getTime(time)
</script>

object :
Add, delete, modify and check the object

let goods = {
// attribute
name: ' Shrimp catcher ',
age: 18,
address: " Under the hole of Hong Kong Zhuhai Macao Bridge ",
// Method
sing: function () {
document.write(' Youth is not always in , Get in love </br>')
}
}
// Call the property
document.write(goods.name + "<br>") // Shrimp catcher
document.write(goods['age'] + "<br>") //18
// Calling method
goods.sing() // Youth is not always in , Get in love
// Methods of adding objects from the outside
goods.run = function () {
document.write(' Remember to run five kilometers every day !<br>')
}
goods.run() // Remember to run five kilometers every day !
// Methods of adding attributes from the outside
goods.skill = " Across mountains and seas "
document.write(goods['skill'] + "<br>") // Across mountains and seas
Traversing objects :

let obj = {
uname: 'andy ', age: 18,
sex: ' male '
}
for (let k in obj) {
document.write(k + '\t') // Print attribute name
document.write(`${
obj[k]} `)// Print attribute values
document.write(`<strong color='red'>${
obj.k} </strong> <br>`)// undefined Is not workable , Unless there is k This property name
}
Math Built-in objects
Math.random() Brief notes : Left closed right away Section , No numbers in brackets !
Math.random() // A floating point pseudo-random number , stay 0( Include 0) and 1( barring ) Between
Math.ceil(1.5) //2 The ceiling , Rounding up
Math.floor(2.4) //2 The floor , Rounding down
Math.round(-1.5) // -1 Function returns the nearest integer to which a number is rounded .
Math.round(2.5) // 3 Function returns the nearest integer to which a number is rounded .
Math.pow(8, 2) // 64 Return cardinality (base) The index of (exponent) The next power
- How to generate
0-10And the random integers ?
Math.floor(Math.random()*(11))
Math.floor(Math.random() * (10 + 1))
- How to generate
5-10Random integer of ?
Math.floor(Math.random() * (5 + 1)) + 5
- How to generate
N-MRandom integer between
Math.floor(Math.random() * (M - N + 1)) + N
// encapsulation random number min To max Between
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
Student information sheet case
<!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>
<style> table {
width: 600px; text-align: center; } table, th, td {
border: 1px solid #ccc; border-collapse: collapse; } caption {
font-size: 18px; margin-bottom: 10px; font-weight: 700; } tr {
height: 40px; cursor: pointer; } table tr:nth-child(1) {
background-color: #ddd; } table tr:not(:first-child):hover {
background-color: #eee; } </style>
</head>
<body>
<script> let students = [ {
name: ' Xiao Ming ', age: 18, gender: ' male ', hometown: ' Hebei Province '}, {
name: ' Xiaohong ', age: 19, gender: ' Woman ', hometown: ' Henan province '}, {
name: ' Xiaogang ', age: 17, gender: ' male ', hometown: ' Shanxi Province '}, {
name: ' Xiao Li ', age: 18, gender: ' Woman ', hometown: ' Shandong Province '} ] document.write(`<table> <caption> <h2> Student list </h2> </caption> <tr> <th> Serial number </th> <th> full name </th> <th> Age </th> <th> Gender </th> <th> hometown </th> </tr>`) for (let i = 0; i < students.length; i++) {
let student = students[i]; document.write(`<tr>`) document.write(`<td>${
i + 1}</td>`) for (let k in student) {
document.write(`<td>${
student[k]}</td>`) // k Is to get the property name of the object , Object name [k] It's getting Property value // Be sure to remember : k Is to get the property name of the object , Object name [k] It's getting Property value } document.write(`</tr>`) } document.write(`</table>`) </script>
</body>
</html>

storage
Simple type Also called basic data type or value type , Complex types are also called Reference type .
- Value type : Simple data type / Basic data type , What is stored in the storage time variable is Value itself , So it's called value type
string ,number,boolean,undefined,null - Reference type : Complex data type , Stored in storage time variables Just the address ( quote ), So it's called reference data type
adoptnewKeyword created objects ( System object 、 Custom object ), Such asObject、Array、Dateetc.
// Complex data type
let obj = {
uname: 'andy ', age: 18,
sex: ' male '
}
let obj2 = obj;
obj2.age = 20;
alert(`${
obj.age}, ${
obj2.age}`) //20,20
// Simple data type
let num1 = 30
let num2 = num1
num2 = 10
alert(`${
num2}, ${
num1}`) //10, 30
Brief notes : Simple data type value storage , Complex data types are stored by address
1、 Stack ( operating system ): Automatically allocate, release and store by the operating system The parameter value of the function 、 The value of a local variable etc. . Its operation mode is similar to that in data structure
The stack ;
Simple data types are stored in Stack Inside
2、 Pile up ( operating system ): Store complex types ( object ), Release is usually assigned by the programmer , If programmers don't release , from Garbage collection mechanism Recycling .
The reference data type is stored in Pile up Inside


边栏推荐
- IPhone 6 plus is listed in Apple's "retro products" list
- 绕过ObRegisterCallbacks需要驱动签名方法
- 深拷貝 事件總線
- 8 examples of using date commands
- Bom Dom
- spfa AcWing 851. SPFA finding the shortest path
- Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
- About the loading of layer web spring layer components, the position of the layer is centered
- 架构师必须了解的 5 种最佳软件架构模式
- spfa AcWing 852. spfa判断负环
猜你喜欢

Linear DP acwing 902 Shortest editing distance

Direct control PTZ PTZ PTZ PTZ camera debugging (c)

Floyd AcWing 854. Floyd求最短路

8 examples of using date commands

bellman-ford AcWing 853. Shortest path with side limit

This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry

AI mid stage technology research

Dijkstra AcWing 850. Dijkstra finding the shortest circuit II

Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution

What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
随机推荐
Wechat official account payment prompt MCH_ ID parameter format error
Enhance network security of kubernetes with cilium
Mui WebView down refresh pull-up load implementation
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
High performance erasure code coding
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
Interesting interview questions
bellman-ford AcWing 853. Shortest path with side limit
线性DP AcWing 897. 最长公共子序列
应用LNK306GN-TL 转换器、非隔离电源
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
移动式布局(流式布局)
Hash table acwing 841 String hash
8 examples of using date commands
Deep Copy Event bus
正确遍历EntryList方法
Dijkstra AcWing 850. Dijkstra求最短路 II