JavaScript-[Week 4]

文章来源于网上收集和自己原创,若侵害到您的权利,请您及时联系并删除

array

Know what an array is and its application scenarios, and master the syntax of array declaration and access.

1.What is an array?

Array: (Array) is a type of data that can be stored in ordertype of data

[Why array] :
Thinking: What if I want to save the names of all the students in a class?

Usage scenario : If there is multiple data, it can be saved in an array and then placed in a variable. Management is very convenient.

2. Basic use of arrays

2.1 Define arrays and array cells

Declaration syntax

let 数组名 = [数据1,数据2, ... ,数据n]

let arr = new Array(数据1,数据2, ... ,数据n)
<script>
  // 1. 语法,使用 [] 来定义一个空数组
  // 定义一个空数组,然后赋值给变量 classes
  // let classes = [];

  // 2. 定义非空数组
  let classes = ['小明', '小刚', '小红', '小丽', '小米']
</script>

By []defining an array, real data can be stored in the data, such as Xiao Ming, Xiao Gang, Xiao Hong, etc. These are all data in the array. These data are called array units, and the array units are separated by English commas.

2.2 Accessing arrays and array indexes

  • Arrays are saved in order, so each data has its own number
  • The numbers in the computer start from 0, so Xiao Ming’s number is 0, Xiao Gang’s number is 1, and so on.
  • In an array, the number of data is also called the index or subscript.
  • Arrays can store any type of data

Using an array to store data is not the ultimate goal. The key is to be able to access the data (units) in the array at any time. In fact, JavaScript numbers each data unit in the array, and you can easily access the data units in the array through the number of the data unit in the array.

We call the number of the data unit in the array the index value, and some people call it the subscript.

The index values ​​are actually arranged according to the position of the data units in the array. Note that they 0start from , as shown in the following figure:

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

Observe the above figure. The index value corresponding to the data unit [Xiao Ming] is [0], and the index value corresponding to the data unit [Xiao Hong] is [2].

<script>
  let classes = ['小明', '小刚', '小红', '小丽', '小米']
  
  // 1. 访问数组,语法格式为:变量名[索引值]
  document.write(classes[0]) // 结果为:小明
  document.write(classes[1]) // 结果为:小刚
  document.write(classes[4]) // 结果为:小米
  
  // 2. 通过索引值还可以为数组单重新赋值
  document.write(classes[3]) // 结果为:小丽
  // 重新为索引值为 3 的单元赋值
  classes[3] = '小小丽'
  document.wirte(classes[3]); // 结果为: 小小丽
</script>

2.3 Data unit value type

An array is a collection of data, and its unit values ​​can be of any data type.

<script>
  // 6. 数组单值类型可以是任意数据类型

  // a) 数组单元值的类型为字符类型
  let list = ['HTML', 'CSS', 'JavaScript']
  // b) 数组单元值的类型为数值类型
  let scores = [78, 84, 70, 62, 75]
  // c) 混合多种类型
  let mixin = [true, 1, false, 'hello']
</script>

2.4 Array length attribute

Again, arrays are not a new data type in JavaScript, they are object types.

<script>
  // 定义一个数组
  let arr = ['html', 'css', 'javascript']
  // 数组对应着一个 length 属性,它的含义是获取数组的长度
  console.log(arr.length) // 3
</script>

some terms

  • Element: Each data stored in the array is called an array element.
  • Subscript: the number of the data in the array
  • Length: The number of data in the array, obtained through the length attribute of the array

2.5 Traverse the array ( 重点)

Iterate over the elements in the output array

Use a loop to access each element in the array, usually using a for loop to traverse

  • grammar:
for(let i = 0;i < 数组名.length; i++){
    
    
	数据名[i]
}

let nums = [10,20,30,40,50]
for(let i = 0;i < nums.length; i++){
    
    
	document.write(nums[i])
}

practise:

  1. Array summation
    Requirement: Find the sum and average of all elements in the array [2,6,1,7, 4]
    Analysis:
    ①: Declare a summation variable sum.
    ②: Traverse this array and add each array element to sum.
    ③: Divide the summation variable sum by the length of the array to get the average value of the array.

  2. Find the maximum and minimum values ​​of an array
    Requirement: Find the maximum value in the array [2,6,1,77,52,25,7]
    Analysis:
    ①: Declare a variable max that holds the largest element.
    ②: The default maximum value can be the first element in the array.
    ③: Traverse this array and compare each array element with max.
    ④: If the array element is greater than max, store the array element into max, otherwise continue to the next round of comparison.
    ⑤: Finally output this max
    expansion:
    自己求一下最小值

3. Two-dimensional array

A two-dimensional array is an array within an array

3.1 Create a two-dimensional array

3.1.1 Direct initialization

The values ​​of all elements are known and can be directly defined and initialized.

// 用 new Array对象创建一个二维数组,且元素的值都已知
let arr1 = new Array(new Array(1,2,3,4),new Array(2,3,4,5),new Array(3,4,5,6));
console.log(arr1[1])	// 元素是一个数组
console.log(arr1[0][1])		// 元素是1



// 用字面量值[] 创建一个 3行3列 的二维数组,且元素的值都已知
let arr1 = [
	[1,2,3,4],
	[2,3,4,5],
	[3,4,5,6],
]
console.log(arr1[0])	// 元素是一个数组
console.log(arr1[1][2])		// 元素是5

3.1.2 Loop creation

The values ​​of the elements in the two-dimensional array are unknown, and the two-dimensional array cannot be initialized directly (the array requires user input)

let row = 2,column = 3
let arr = []	// 声明一维数组
for(let i = 0; i < row; i++){
    
    
	arr[i] = [];
	for (let j = 0; j < column; j++){
    
    
		arr[i][j] = prompt("请输入第" + (i * column + j + 1) + "个数")
	}
}

console.log(arr)

3.2 Traversal of two-dimensional arrays


// 用 for循环求和
let arr = [
	[1,4,6,8],
	[23,5,4,7],
	[12,34,9,11],
]
let sum = 0
for(let i = 0; i < arr.length; i++){
    
    	// 遍历二维数组的每个元素
	for(let j = 0; j < arr.length; j++){
    
    	// 求二维数组的所有元素
		sum += arrr[i][j]
	}
}
console.log("二维数组:" + arr)	// 输出二维数组
console.log("二维数组中所有元素的和:" + sum)		// 输出元素之和


// 用 for...in语句求和
let arr2 = [
	[1,4,6,8],
	[23,5,4,7],
	[12,34,9,11],
]
let sum2 = 0
for(let i in arr2){
    
    	// 遍历二维数组的每个元素
	for(let j in arr2[i]){
    
    	// 求二维数组的所有元素
		sum2 += arrr2[i][j]
	}
}
console.log("二维数组:" + arr2)	// 输出二维数组
console.log("二维数组中所有元素的和:" + sum2)		// 输出元素之和

4. Operation array

As an object data type, arrays not only have lengthattributes that can be used, but also provide many methods. Arrays are essentially data collections, and operating data is nothing more than syntax:
Insert image description here

  1. pushDynamically add a cell to the end of an array
  2. unshitDynamically add a cell to the head of an array
  3. popDelete last unit
  4. shiftDelete the first unit
  5. spliceDynamically delete any unit

When using the above four methods, operations are performed directly on the original array. That is, if any method is successfully called, the original array will be changed accordingly. lengthAnd there is no confusion when adding or removing cells .

4.1 New

Use push to add elements (data) to the array

  1. 数组.push()Method adds one or more elements to the end of an array and returns the new length of the array ( 重点)
  • grammar:
arr.push(元素1, ..., 元素n)

like:

let arr = ["red","green"]
arr.push("black")
console.log(arr)	// ["red","green","black"]

let arr = ["red","green"]
arr.push("black","yellow")
console.log(arr)	// ["red","green","black","yellow"]
  1. arr.unshift(新增的内容) Method adds one or more elements to the beginning of an array and returns the new length of the array
  • grammar:
arr.unshift(元素1, ..., 元素n)

like:

let arr = ["red","green"]
arr.unshift("black")
console.log(arr)	// ["black","red","green"]

let arr = ["red","green"]
arr.unshift("black","yellow")
console.log(arr)	// ["black","yellow","red","green"]

Summarize

  1. Which method should you use to add data elements to the end of an array?
    arr.push()
    can add one or more array elements
    and returns the array length.
  2. Which method should be used to add data elements to the beginning of the array?
    arr.unshift()
    can add one or more array elements
    and returns the array length.
  3. What is the key thing to remember?
    arr.push()

Case
Array screening
requirements: Select elements greater than or equal to 10 in the array [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] and put them into a new array Analysis: ①: Declare a new
array
with To store new data newArr
②: Traverse the original old array and find elements greater than or equal to 10
③: Append to the new array newArr in turn

Case
Requirement for removing 0 from array
: remove 0 from array [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] to form a new array that does not contain 0. Analysis: ①: Declare
a
new The array is used to store new data newArr
②: Traverse the original old array and find the elements that are not equal to 0
③: Append to the new array newArr in sequence

4.2 Delete

Ability to delete array elements (data)

  1. 数组. pop() Method removes the last element from an array and returns the value of that element
  • grammar
arr.pop()

like:

let arr = ["red","green"]
arr.pop()
console.log(arr)	// ["red"]
  1. 数组. shift()Method removes the first element from an array and returns the value of that element
  • grammar
arr.shift()

like:

let arr = ["red","green"]
arr.shift()
console.log(arr)	// ["green"]

Case
Required usage scenarios:

  1. In random draws, winning users need to be deleted from the array, and repeated draws are not allowed.
  2. Click the delete button and the relevant data will be deleted from the product data

后期课程我们会用到删除操作,特别是 splice

Insert image description here
3. 数组. splice() Method to delete specified elements

  • grammar:
arr.splice(start,deleteCount)

arr.splice(起始位置,删除几个元素)

explain:

  • start starting position:
    specifies the starting position of modification (counting from 0)
  • deleteCount:
    Indicates the number of array elements to be removed. Optional. If omitted, it defaults to deleting from the specified starting position to the end.

like:

let arr = ["red","green"]
arr.splice(0,1)
console.log(arr)	// ["green"]

Summarize

  1. Which method should be used to delete a data element at the end of an array? With parameters?
    arr.pop()
    takes no parameters and
    the return value is the deleted element.
  2. Which method should be used to delete a data element from the beginning of the array? With parameters?
    arr.shift()
    takes no parameters and
    the return value is the deleted element
  3. Want to specify which array element to use when deleting it? Is it commonly used in development? What are the usage scenarios?
    arr.splice (starting position, number of deleted items)
    is very commonly used in development, such as random draws, deleting specified products, etc.
<script>
  // 定义一个数组
  let arr = ['html', 'css', 'javascript']

  // 1. push 动态向数组的尾部添加一个单元
  arr.push('Nodejs')
  console.log(arr)
  arr.push('Vue')

  // 2. unshit 动态向数组头部添加一个单元
  arr.unshift('VS Code')
  console.log(arr)

  // 3. splice 动态删除任意单元
  arr.splice(2, 1) // 从索引值为2的位置开始删除1个单元
  console.log(arr)

  // 4. pop 删除最后一个单元
  arr.pop()
  console.log(arr)

  // 5. shift 删除第一个单元
  arr.shift()
  console.log(arr)
</script>

5. Array sorting-bubble sorting

  • Bubble sort is a simple sorting algorithm.
  • It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted.
  • The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through swapping.
  • For example, the array [2,3,1,4,5] becomes [1,2,3,4,5] or [5,4,3,2,1] after sorting

analyze:
Insert image description here

数组. sort()Methods can be sorted

let arr = [4, 2, 5, 1, 3]
// 1.升序排列写法
arr.sort(function (a, b) {
    
    
return a - b
})
console.log(arr) // [1, 2, 3, 4, 5]
// 降序排列写法
arr.sort(function (a, b) {
    
    
return b - a
})
console.log(arr) // [5, 4, 3, 2, 1]

6. Comprehensive cases

Generate a column chart based on data.
Requirements: Users input four quarters of data and a column chart can be generated
. Analysis:

  1. It needs to be entered 4 times, so you can put the 4 data into an array.
    Use a loop to pop up the box 4 times and save it into the array at the same time.
  2. Traverse the array, generate 4 column charts based on the data, render and print them to the page.
    The column chart is a div box with a fixed width and a height that is the data input by the user.
    The div contains the displayed number and the nth quarter.
    Insert image description here

Guess you like

Origin blog.csdn.net/qq_44625715/article/details/132962399