当前位置:网站首页>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-10
And the random integers ?
Math.floor(Math.random()*(11))
Math.floor(Math.random() * (10 + 1))
- How to generate
5-10
Random integer of ?
Math.floor(Math.random() * (5 + 1)) + 5
- How to generate
N-M
Random 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
adoptnew
Keyword created objects ( System object 、 Custom object ), Such asObject、Array、Date
etc.
// 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
边栏推荐
- 上手报告|今天聊聊腾讯目前在用的微服务架构
- 获取文件版权信息
- std::vector批量导入快速去重方法
- 百款拿来就能用的网页特效,不来看看吗?
- Efficiency comparison between ArrayList and LinkedList
- 1380. Lucky numbers in the matrix [two-dimensional array, matrix]
- Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
- 哈希表 AcWing 840. 模拟散列表
- BOM DOM
- 线性DP AcWing 896. 最长上升子序列 II
猜你喜欢
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
深拷贝 事件总线
染色法判定二分图 AcWing 860. 染色法判定二分图
Linear DP acwing 897 Longest common subsequence
ArrayList与LinkedList效率的对比
线性DP AcWing 898. 数字三角形
通过反射执行任意类的任意方法
JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
JDBC prevent SQL injection problems and solutions [preparedstatement]
AI mid stage technology research
随机推荐
浏览器存储方案
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
Dijkstra AcWing 850. Dijkstra finding the shortest circuit II
async/await 异步函数
区间DP AcWing 282. 石子合并
Intel internal instructions - AVX and avx2 learning notes
Sse/avx instruction set and API of SIMD
Drools executes string rules or executes a rule file
Linear DP acwing 895 Longest ascending subsequence
Fluent fluent library encapsulation
Sweetheart leader: Wang Xinling
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
AI mid stage technology research
JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
BOM DOM
Leetcode - Sword finger offer 59 - I, 59 - II
JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
VLAN experiment
Lekao: 22 year first-class fire engineer "technical practice" knowledge points