当前位置:网站首页>Take you to understand JS array
Take you to understand JS array
2022-07-29 04:43:00 【JS human column force】
js Array
What is an array (Array)?
Object finite storage key value set , But in some cases, using key value pairs to access is not convenient ;
For example, some columns of goods 、 user 、 hero , Include HTML Elements , How do we store them together ?
At this time, we need an orderly set , The elements inside are arranged in a certain order ;
This ordered set , We can get it by index ;
This structure is an array (Array);
Arrays and objects are data structures that hold multiple data

How to create an array
Array is a special object type
- We can go through [] To create an array
const arr = ['a','b','c','d']
- adopt new Keyword to create an array
const arr2 = new Array() // What is created is an empty array
const arr3 = new Array('a','b','c','d')
If you fill in an integer , Is to set the length of the array
const arr4 = new Array(5) // The array length is 5
Array elements from 0 Numbered starting ( Indexes index)
Basic operations of arrays
The addition of arrays 、 Delete method
- Add or remove elements at the end of the array :
push: Add elements at the end of the array ( You can add more than one at the same time )
pop: Delete an element from the end of the array ( Only one... Can be deleted at a time )
let arr = ['abc','cba','def']
arr.push(' I'm new here ',' I'm new here 2')
arr.pop()

Add or remove elements at the beginning of the array
shift: Delete the first element at the beginning of the array , The entire array element moves forwardunshift: Add an element at the beginning , Move the entire other array elements backward
Be careful :push/pop The method runs faster , and shift/unshift It's slow
Because no matter forward (unshift) Add or forward (shift) Delete a bit , Everything behind the array must be moved
What should we do if we want to add or delete elements in the middle of the array ?
splice Method : It can be said to be a sharp tool for processing arrays , It can do everything : add to , Delete and replace
grammar :
array.splice(start[,deleteCout][, item1[item2[,…]]])
from start Position start , Processing elements in an array ;
deleteCout: Number of elements to delete , If 0 Or a negative number means not to delete ;
item1,item2,…: When adding elements , Elements that need to be added
arr.splice(1,1) // Delete an element
arr.splice(1,0,' I'm new here 1',' I'm new here 2') // Add two elements
arr.splice(1,2,' Replace 1',' Replace 2')
Be careful : This method will modify the original array
length attribute
length Property is used to get the length of the array
When we modify the array ,length Properties are automatically updated
length Another point of the attribute is that it can be written
If we manually add one larger than the default length The numerical , Then it will increase the length of the array
But if we reduce it , The array will be truncated
var arr = [' Hello ', ' The world ', 'hello', 'world']
arr.length = 10
console.log(arr)
arr.length = 2
console.log(arr)

Traversal of array
- ordinary for loop
var arr = [' Hello ', ' The world ', 'hello', 'world']
for(let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
- for… in Traverse , Get index
var arr = [' Hello ', ' The world ', 'hello', 'world']
for(let index in arr) {
console.log(arr[index])
}
- for … of Traverse Traverse to every element
var arr = [' Hello ', ' The world ', 'hello', 'world']
for(let item of arr) {
console.log(item)
}
Array methods - slice、concat、join
arr.slice Method : Used to intercept the array ( Similar to string slice Method )
arr.slice([begin[,end]])
contain bigin Elements , But it doesn't include end Elements
console.log(arr.slice(2,3))
arr.concat Method : Create a new array , It contains values from other arrays and other items
var new_array = old_array.concat(value1[,value2[,…[,valueN]]])
let arr = ['a', 'b', 'c']
let arr2 = [1, 2, 3]
let arr3 = arr2.concat(arr)
console.log(arr3)

arr.join Method : Concatenates all elements of an array into a string and returns the string
arr.join([separator])
let arr = [' Hello ',' The world ']
console.log(arr.join(''))
Insert picture description here
Array methods - Look for the element
indexOf Method : Find the index of an element
arr.indexOf(searchElement[,fromIndex])
from fromIndex Start looking for , If found, return the corresponding index , No return found -1
There are also for searching from the last position lastIndexOf Method
arr.includes Method : Determine whether an array contains an element
arr.includes(valueToFind[ ,fromIndex])
From the index from Begin your search item, Return if found true
const arr = ['a','b','c','d']
console.log(arr.includes('b')) // true
find and ·findIndex Directly find the element or the index of the element
Array sorting -sort/reverse
sort The method is also a higher-order function , Used to sort arrays , And generate a new array after sorting
arr.sort([compareFuncion])
If compareFunction(a,b) Less than 0, that a It will be arranged to b front ;
If compareFunction(a,b) be equal to 0,a and b The relative position of ;
If compareFunction(a,b) Greater than 0,b It will be arranged to a front ;
in other words , Who's younger, who's in front
const arr = [3,4,5,6,1,3,5,7]
arr.sort(function(a,b) {
return b - a
})
console.log(arr)
reverse() Method Invert the position of the elements in the array , And return the array
Array other methods
forEach Method
Handwriting froEach function
Array.prototype.MyForCach = function(fn) {
for(let i = 0; i<this.length; i++) {
fn(this[i],i,this)
}
}
边栏推荐
- mpc5744p简介与OpenSDA固件更新
- Unity Foundation (3) -- various coordinate systems in unity
- post导出数据,返回
- EF core: one to one, many to many configuration
- Configure st-gcn environment record [Google lab]
- Make a virtual human with zego avatar | virtual anchor live broadcast solution
- Integration of Nan causes in pytorch training model
- Laya中的A星寻路
- File operation (Advanced C language)
- OpenCV环境搭建
猜你喜欢

Record the Niua packaging deployment project

Implementation of img responsive pictures (including the usage of srcset attribute and sizes attribute, and detailed explanation of device pixel ratio)

Flutter 手势监听和画板实现

TypeError: Cannot read properties of undefined (reading ‘then‘)
![Understand the Internet giant [the war between China and Taiwan] and the development thinking of China and Taiwan](/img/6c/f24407133663c0e19d6fa05c611341.png)
Understand the Internet giant [the war between China and Taiwan] and the development thinking of China and Taiwan

VScode 一键编译和调试

On quotation

Ethernet of network

ssm整合增删改查

用 ZEGO Avatar 做一个虚拟人|虚拟主播直播解决方案
随机推荐
After the spinning up installation is completed, use the tutorial to test whether it is successful. There are library "Glu" not found and 'from pyglet.gl import * error solutions
Actual combat of flutter - DIO of request encapsulation (II)
网络之以太网
Software test interview questions (4)
Pyqt5 learning pit encounter and pit drainage (2) buttons in qformlayout layout cannot be displayed
读懂 互联网巨头 【中台之战】 以及 中台 发展思维
Vscode configuration makefile compilation
Idea small settings
Tower of Hanoi classic recursion problem (C language implementation)
New year's greetings from programmers
Recommendation system of online education
JVM (heap and stack) memory allocation
Implementation of img responsive pictures (including the usage of srcset attribute and sizes attribute, and detailed explanation of device pixel ratio)
I++ and ++i details
[c language] PTA 7-55 query fruit price
Various configurations when pulsar starts the client (client, producer, consumer)
2022杭电多校联赛第四场 题解
Mysql:The user specified as a definer (‘root‘@‘%‘) does not exist 的解决办法
Dasctf2022.07 empowerment competition
Niuke IOI weekly 27 popularity group