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


边栏推荐
- 堆 AcWing 838. 堆排序
- About the loading of layer web spring layer components, the position of the layer is centered
- Openssh remote enumeration username vulnerability (cve-2018-15473)
- The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph
- Linear DP acwing 895 Longest ascending subsequence
- Bom Dom
- Linear DP acwing 898 Number triangle
- JSON serialization and parsing
- Linear DP acwing 896 Longest ascending subsequence II
- Redis introduction, scenario and data type
猜你喜欢

浏览器存储方案

模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计

Drools dynamically add, modify, and delete rules

上手报告|今天聊聊腾讯目前在用的微服务架构

Dijkstra AcWing 850. Dijkstra求最短路 II

8 examples of using date commands

Sweetheart leader: Wang Xinling

Direct control PTZ PTZ PTZ PTZ camera debugging (c)

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

Interview with meituan, a 34 year old programmer, was rejected: only those under the age of 30 who work hard and earn little overtime
随机推荐
bellman-ford AcWing 853. Shortest path with side limit
Browser storage scheme
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
Deep copy event bus
[I'm a mound pytorch tutorial] learning notes
Modular commonjs es module
China traffic sign detection data set
深拷贝 事件总线
FBX import under ue4/ue5 runtime
Leetcode - Sword finger offer 59 - I, 59 - II
移动式布局(流式布局)
线性DP AcWing 899. 编辑距离
Distributed machine learning framework and high-dimensional real-time recommendation system
[ybtoj advanced training guidance] cross the river [BFS]
Leetcode - Sword finger offer 51 Reverse pairs in an array
ArrayList与LinkedList效率的对比
通过反射执行任意类的任意方法
Efficiency comparison between ArrayList and LinkedList
基于STM32的OLED 屏幕驱动
Linear DP acwing 902 Shortest editing distance