当前位置:网站首页>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)
}
}
边栏推荐
- Pyqt5 learning pit encounter and pit drainage (1) unable to open designer.exe
- Classes and objects (I)
- iOS面试准备 - ios篇
- File operation (Advanced C language)
- [C language] power table of 3 generated by PTA 7-53
- EF core: one to one, many to many configuration
- 软件测试面试题(四)
- VScode配置makefile编译
- Christmas tree web page and Christmas tree application
- Dabao and Erbao
猜你喜欢

Hengxing Ketong invites you to the 24th China expressway informatization conference and technical product exhibition in Hunan

spinning up安装完使用教程测试是否成功,出现Library“GLU“ not found和‘from pyglet.gl import *错误解决办法

Detailed comparison of break and continue functions

un7.28:redis客户端常用命令。

iOS面试准备 - ios篇

论pyscript使用感想(实现office预览)

redux快速上手

GCC基础知识

Deploy Jenkins using containers

在线教育的推荐系统
随机推荐
settings.xml
[C language] PTA 7-52 finding the sum of the first n terms of a simple interleaved sequence
Actual combat of flutter - DIO of request encapsulation (II)
EF Core: 一对一,多对多的配置
MySQL - 深入解析MySQL索引数据结构
Mongo shell interactive command window
Integration of Nan causes in pytorch training model
Ethernet of network
Exception resolution: error of not finding edu.stanford.nlp.semgraph.semgrex.semgrexpattern in cococaption package
Simply change the picture color
LeetCode(剑指 Offer)- 53 - I. 在排序数组中查找数字 I
redux快速上手
Basic operation of queue
在线教育的推荐系统
WebRTC实现简单音视频通话功能
Pyscript cannot import package
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
On quotation
JVM (heap and stack) memory allocation
使用近场探头和电流探头进行EMI干扰排查