当前位置:网站首页>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


边栏推荐
- Leetcode - Sword finger offer 59 - I, 59 - II
- 线性DP AcWing 897. 最长公共子序列
- Floyd AcWing 854. Floyd求最短路
- spfa AcWing 851. spfa求最短路
- 移动式布局(流式布局)
- AI mid stage technology research
- Do you know all the interface test interview questions?
- BOM DOM
- OpenCV中cv2.VideoWriter_fourcc()函数和cv2.VideoWriter()函数的结合使用
- 架构师必须了解的 5 种最佳软件架构模式
猜你喜欢

趣味 面试题

Simple use of drools decision table

哈希表 AcWing 841. 字符串哈希

线性DP AcWing 902. 最短编辑距离

PR 2021 quick start tutorial, learn about the and functions of the timeline panel

JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
![JDBC 预防sql注入问题与解决方法[PreparedStatement]](/img/32/f71f5a31cdf710704267ff100b85d7.png)
JDBC 预防sql注入问题与解决方法[PreparedStatement]

3 A VTT端接 稳压器 NCP51200MNTXG资料

Linear DP acwing 895 Longest ascending subsequence

Sweetheart leader: Wang Xinling
随机推荐
Oracle从入门到精通(第4版)
Do you know all the interface test interview questions?
JDBC 预防sql注入问题与解决方法[PreparedStatement]
spfa AcWing 851. spfa求最短路
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
Execute any method of any class through reflection
[ybtoj advanced training guide] similar string [string] [simulation]
Record the range of data that MySQL update will lock
BOM DOM
Is the neural network (pinn) with embedded physical knowledge a pit?
Heap acwing 839 Simulated reactor
Fluent fluent library encapsulation
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
8 examples of using date commands
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
Browser storage scheme
线性DP AcWing 897. 最长公共子序列
Heap acwing 838 Heap sort
百款拿来就能用的网页特效,不来看看吗?
Rust search server, rust quick service finding tutorial