Preface
In our daily development, we deal with the interface the most. The front-end accesses the back-end interface, and then re-processes the interface data and renders it to the page.
The secondary treatment process is a test Coder
to Array
whether skilled and which method to use in which scenario best deal.
Editor, I encountered the Array
in recent development. When dealing with complex business requirements, I did not expect Array
have a similar method, and then combine the methods to solve the current problem.
article took a week to finish writing after work hours. After reading it, likes and forwards are my biggest support.
Array traversal method
Will not change the traversal method of the original array
forEach()
forEach()
method executes the given function once for each item in the array in ascending order.
Syntax
arr.forEach(callback(currentValue , index , array) ,thisArg)
currentValue
: the current item value of the arrayindex
: the index of the current item in the arrayarr
: the array object itselfthisArg
: Optional parameter. When the callback functioncallback
is executed, it is used as the value ofthis
note
- If the arrow function expression used to pass in the function parameters, the
thisArg
parameter will be ignored because the arrow function is lexically bound to thethis
value. forEach
will not directly change the object that calls it, but that object may becallback
function.every
will not change the original array.
//防盗贴:微信公众号: 前端自学社区
const arr = [2,3,4,1,44]
arr.forEach(val =>{
console.log(`值为${val*2}`)
})
console.log(`原数组为${arr}`);
// 值为4
// 值为6
// 值为8
// 值为2
// 值为88
// 原数组为2,3,4,1,44
reduce()
reduce()
array element accumulator, returns a combined result value.
Syntax
arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
accumulator
: accumulator, the default is the first value of the array elementcurrentValue
: current valueindex
: current element index <font style="color:red">optional</font>array
: array <font style="color:red">optional</font>initialValue
: Initial value<font style="color:red">optional</font>
reduce
has two parameters, one is the callback function, and the other is the initial value.
It has two values:
- When it provided
initialValue
initial value,accumulator
valueinitialValue
,currentValue
valuearray of a first value
- When it provided
- When not provided
initialValue
initial value,accumulator
first value is an array,currentValue
for the second value.
- When not provided
Note
- If the array is empty and does not provide
initialValue
initial value, it throwsTypeError
. - If the array has one element, and does not provide
initialValue
or provideinitialValue
, the array is empty, then the only value to be returned does not performcallback
callback function.
Sum
//防盗贴:微信公众号: 前端自学社区/
const arr = [1, 2, 3, 4]
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 10)
console.log(sum) //20
// accumulator 累计器
// currentValue 当前值
// initialValue 累计 初始值 为10
//10 + 1 + 2 + 3 + 4
## 注意
// 回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:
// 如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;
// 如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
Calculate the value in the object
To accumulate the values contained in the object array, you must provide an initial value so that each item can pass your function correctly.
/*
* @Description:
* @Author: 微信公众号: 前端自学社区
* @Date: 2021-08-07 00:53:51
* @LastEditTime: 2021-08-07 00:53:51
* @LastEditors: Do not edit
*/
const data = [
{
date: '2021-8-1',
income: 200
},
{
date: '2021-8-2',
income: 400
},
{
date: '2021-8-3',
income: 300
},
]
console.log(`总收入: ${data.reduce( (pre,currentValue) => pre + currentValue.income,0)}`);
//总收入: 900
two-dimensional array to one-bit array
const array = [[1,2],[3,4]]
console.log(array.reduce((a,b) => a.concat(b)));
//[ 1, 2, 3, 4 ]
find()
find()
returns the element object or element value that meets specific conditions, and returns undefined
Syntax
arr.find((element,index,array), thisArg)
element
: current elementindex
: current element index <font style="color:red">optional</font>array
: The array itself <font style="color:red">optional</font>thisArg
: The objectthis
when executing callbacks. <font style="color:red">Optional</font>
// 从数据中找出第一个满足特定条件的对象
const data = [
{
name:'张三',
article: 3
},
{
name:'老王',
article: 9
},
{
name:'老李',
article: 10
}
]
console.log(data.find(item => item.article > 9 ));
// { name: '老李', article: 10 }
findIndex()
findIndex()
returns the index of the first element in the array that meets the criteria, if not, it returns -1
.
Syntax
arr.findIndex((element,index,array), thisArg)
element
: current elementindex
: current element index <font style="color:red">optional</font>array
: The array itself <font style="color:red">optional</font>thisArg
: The objectthis
when executing callbacks. <font style="color:red">Optional</font>
const arr = [22,33,44,55]
console.log(arr.findIndex(val => val > 33)); //2
console.log(arr.findIndex(val => val > 99)); //-1
key()
key()
returns a new Array Iterator object that contains the key for each index in the array.
Syntax
keys()
Note
- If there are empty original elements in the array, they will also be added to the traversed queue when obtaining the key.
const inputModal = [
{
name:''
},
{
age:''
},
{
hobby:''
}
]
for(const key of inputModal.keys()){
console.log(key)
}
// 0
// 1
// 2
const arr = [1,2,,3]
for(const key of arr.keys()){
console.log(key);
}
// 0
// 1
// 2
// 3
//Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组
// 所以 Object.keys(arr) = [ '0', '1', '3' ]
for(const key of Object.keys(arr)){
console.log(key);
}
// 0
// 1
// 3
values()
values()
method returns a new Array Iterator object, which contains the value of each index in the array.
Syntax
arr.values()
const Color = ['red','yelloe','orange']
for(val of Color.values()){
console.log(val);
}
// red
// yelloe
// orange
<hr/>
Return boolean
every()
every
used to determine whether all elements in the array meet a certain condition, and return Boolean value
Syntax
arr.every(callback(currentValue , index , array) ,thisArg)
currentValue
: The current item value of the array <font style="color:red">Required</font>index
: The index of the current item in the array <font style="color:red">optional</font>arr
: The array object itself <font style="color:red">optional</font>thisArg
: Optional parameter. When the callback functioncallback
is executed, it is used as the value ofthis
<font style="color:red">Optional</font>
Note
true
will be returned when all elements meet the conditionsevery
will not change the original array.- If an empty array is passed in,
true
will be returned anyway.
//防盗贴:微信公众号: 前端自学社区
const arr = [2,3,4,1,44]
console.log(arr.every(val => val > 0 )); //true
console.log(arr.every(val => { val > 2 })) //false
some()
some()
used to determine whether an array element meets a certain condition, as long as one element meets, then true
is returned.
Syntax
arr.some(callback(currentValue , index , array) ,thisArg)
currentValue
: The current item value of the array <font style="color:red">required</font>index
: The index of the current item in the array <font style="color:red">optional</font>arr
: The array object itself <font style="color:red">optional</font>thisArg
: Optional parameter. When the callback functioncallback
is executed, it is used as the value ofthis
<font style="color:red">Optional</font>
Note
some()
will not change the array when it is called.- If you test with an empty array, it will return
false
in any case. some()
During the traversal, the element range has been determined, and the elements added during the traversal process will not be added to the traversed sequence.
const arr = [2,3,4,1,44]
console.log(arr.some(val => val > 2)) //true
console.log([].some(val => val > 2 )); //false
const newList = [11,22,33,44]
console.log(newList.some(val => {
newList.push(55)
newList.push(66)
val > 55
})); //false
Do not change the original array, form a new array
filter()
filter()
used to traverse the original array, filter the array elements that meet the conditions, and form new array elements.
Syntax
arr.some(callback(currentValue , index , array) ,thisArg)
currentValue
: The current item value of the array <font style="color:red">Required</font>index
: The index of the current item in the array <font style="color:red">optional</font>arr
: The array object itself <font style="color:red">optional</font>thisArg
: Optional parameters. When the callback functioncallback
is executed, it is used as the value ofthis
<font style="color:red">Optional</font>
Note
filter
does not change the original array, it returns the filtered new array.filter()
When traversing, the element range has been determined, and the elements added during the traversal process will not be added to the traversed sequence.
const arr = [11,22,33,44,55,66]
console.log(arr.filter(val => val > 44 ))
console.log(`原数组为${arr}`);
// [ 55, 66 ]
// 原数组为11,22,33,44,55,66
map()
map()
creates a new array, and the result is the result returned by calling a provided function for each element in the array.
Syntax
arr.map(callback(currentValue , index , array) ,thisArg)
currentValue
: The current item value of the array <font style="color:red">required</font>index
: The index of the current item in the array <font style="color:red">optional</font>arr
: The array object itself <font style="color:red">optional</font>thisArg
: Optional parameter. When the callback functioncallback
is executed, it is used as the value ofthis
<font style="color:red">Optional</font>
Note
map
does not modify the original array itself that calls itmap()
During the traversal, the element range has been determined, and the elements added during the traversal process will not be added to the traversed sequence.
const arr = [1,2,3,4]
console.log(arr.map(val => val*3 )) // [ 3, 6, 9, 12 ]
console.log(arr) // [ 1, 2, 3, 4 ]
<hr/>
Array CRUD
Change the original array method
reverse()
reverse()
method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method will change the original array.
const arr = [1,2,3]
console.log(arr.reverse(11,22,33)) //[ 3, 2, 1 ]
sort()
sort()
method uses the place algorithm to sort and return the array. The default sort order is to the elements at 16111cfa043e13 to the string , and then compare their UTF-16
code unit value sequence
Place Algorithm is an algorithm that uses auxiliary data structures to transform the input. However, it allows a small amount of additional storage space to store auxiliary variables. When the algorithm is running, the input is usually overwritten by the output. The in-place algorithm only updates the input sequence by replacing or exchanging elements.
const arr = [23,11,33,44,1]
console.log(arr.sort()) //[ 1, 11, 23, 33, 44 ]
const arr = [23,11,33,44,1000000000]
console.log(arr.sort())
// [ 1000000000, 11, 23, 33, 44 ]
Delete element
shift()
shift()
method removes from the array first element, and returns the value of the element. This method changes the length of the array.
Syntax
arr.shift()
Note
- The element removed from the array; if the array is empty, it returns
undefined
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'后端'
},
{
id:3,
name:'移动端'
},
{
id:4,
name:'嵌入式开发'
},
]
const deleObj = data.shift()
console.log('==============删除后的元素======================');
console.log(data);
console.log('=================删除后的元素===================');
console.log('===============被删除的元素=====================');
console.log(deleObj);
console.log('================被删除的元素====================');
// ==============删除后的元素======================
// [
// { id: 2, name: '后端' },
// { id: 3, name: '移动端' },
// { id: 4, name: '嵌入式开发' }
// ]
// =================删除后的元素===================
// ===============被删除的元素=====================
// { id: 1, name: '前端' }
// ================被删除的元素====================
pop()
pop()
method deletes the last element from the array and returns the value of that element. This method changes the length of the array.
The usage is similar to shift
Syntax
arr.pop()
Attention
- The element removed from the array; if the array is empty, it returns
undefined
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'后端'
},
{
id:3,
name:'移动端'
},
{
id:4,
name:'嵌入式开发'
},
]
const deleObj = data.pop()
console.log(data);
// [
// { id: 1, name: '前端' },
// { id: 2, name: '后端' },
// { id: 3, name: '移动端' }
// ]
console.log(deleObj);
// { id: 4, name: '嵌入式开发' }
splice()
splice()
method deletes or replaces the or adds new elements in place to modify the array, and returns the modified content in the form of an array. This method will change the original array.
Syntax
array.splice(start,deleteCount, [item1,item2....])
start
: starting indexdeleteCount
: The number of deleted <font style="color:red">optional</font>[item1,item2 .....]
; elements added and replaced from the starting index, <font style="color:red">optional</font>
Note
- An array of deleted elements. If only one element is deleted, an array containing only one element is returned. If no elements are deleted, an empty array is returned.
If only the starting index position is passed, all element objects after the index will be deleted
const data = [ { id:1, name:'前端' }, { id:2, name:'后端' }, { id:3, name:'移动端' }, { id:4, name:'嵌入式开发' }, ] data.splice(1) console.log(data) // [ { id: 1, name: '前端' } ]
Starting from index 2, delete 1 array element object and add two array element objects
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'后端'
},
{
id:3,
name:'移动端'
},
{
id:4,
name:'嵌入式开发'
},
]
data.splice(2,1,...[{id:5,name:'人工智能'},{id:6,name:'大数据开发'}])
console.log(data);
// [
// { id: 1, name: '前端' },
// { id: 2, name: '后端' },
// { id: 5, name: '人工智能' },
// { id: 6, name: '大数据开发' },
// { id: 4, name: '嵌入式开发' }
// ]
Add elements
splice()
Already introduced above
push()
push()
method adds one or more elements to the end of , and returns the new length of the array.
Syntax
arr.push(element1, ..., elementN)
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'后端'
},
]
console.log(data.push({id:3,name:'移动端'})) //3
merged array
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'后端'
},
]
var obj = [
{
id:4,
name:'嵌入式开发'
},
]
// 相当于 data.push({id:4,name:'嵌入式开发'});
Array.prototype.push.apply(data, obj);
console.log(data);
[
{ id: 1, name: '前端' },
{ id: 2, name: '后端' },
{ id: 4, name: '嵌入式开发' }
]
unshift()
unshift()
method adds one or more elements to the at the beginning of the array, and returns the new length of .
const arr = [1,2,3]
console.log(arr.unshift(11,22,33)) //6
console.log(arr) //[ 11, 22, 33, 1, 2, 3 ]
Do not change the original array element method
indexOf()
indexOf()
method returns the first index where the given element can be found in the array, or -1 if it does not exist.
Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex)
searchElement
: the element to findfromIndex
: Search for the first index of the specified element that appears according to the specified index. <font style="color:red">Optional</font>- If the index is greater than or equal to the length of the array, -1 is returned
- If the provided index value is negative, it will be treated as an offset from the end of the array
- If the provided index is negative, the array is still searched from front to back
- If the index provided is 0, the entire array will be searched.
- Default value: 0 (search the entire array).
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.indexOf(3)); //3
console.log(arr.indexOf(9)); //-1
console.log(arr.indexOf(3,4)); //-1
//从索引为 4 的元素进行查找 3, 显然后面没有3 , 返回 -1
Array deduplication
Create a new empty array and use indexOf
to determine whether an element exists in the empty array for the first time.
- If it does not exist, return [<0] and
push
into an empty array.
const newArr = []
arr.forEach(val => {
if(newArr.indexOf(val) < 0){
newArr.push(val)
}
})
console.log(newArr);
// [ 1, 2, 3, 4, 5, 6 ]
lastIndexOf()
lastIndexOf()
finds the index of the last occurrence of an element in the array, and returns -1 if it is not found.
If it does not exist, it returns -1. Search forward from the back of the array, starting from fromIndex
.
Grammar
arr.lastIndexOf(searchElement, fromIndex)
searchElement
: the element to findfromIndex
: Find the first index of the specified element that appears according to the specified index. <font style="color:red">Optional</font>- Reverse search from the specified index position
- The default is the length of the array minus 1 (
arr.length - 1
), that is, the entire array is searched. - If the value is greater than or equal to the length of the array, the entire array will be searched.
- If it is negative, the array will still be searched from back to front.
- If the value is negative and its absolute value is greater than the length of the array, the method returns -1, that is, the array will not be searched.
Note
lastIndexOf
using strictly equal === comparesearchElement
element and the array.
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.lastIndexOf(4)); //7
console.log(arr.lastIndexOf(4,11));
//7 指定的查找的索引 大于 数组的长度, 会进行整个数组查找
console.log(arr.lastIndexOf(4,-33));
// -1 指定的索引为负数,且绝对值大于数组长度, 则返回 -1
console.log(arr.lastIndexOf(4,-5));
//4 指定的索引为负数,且绝对值小于数组长度, 则会 从向前进行查找
inCludes()
includes()
method is used to determine whether an array contains a specified value, according to the situation, if it contains, it returns true, otherwise it returns false.
Syntax
arr.includes(searchElement, fromIndex)
searchElement
: the element to findWhen searching, case sensitive
fromIndex
: Find the first index of the specified element that appears according to the specified index. <font style="color:red">Optional</font>- Search from the specified index
- If it is a negative value, start searching from the index of
array.length + fromIndex
- If
fromIndex
greater than or equal to the length of the array,false
will be returned and the array will not be searched. - Default is 0
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.includes(4)); //true
console.log(arr.includes(4,66)); //false
console.log(arr.includes(1,-1)); //false
concat()
concat()
method is used to merge two or more arrays.
Syntax
var new_array = old_array.concat([arr1][arr2])
Note
concat
method does not changethis
or any array provided as a parameter, but returns a shallow copy , which contains a copy of the same elements combined with the original array- Object reference (not actual object):
concat
Copy the object reference into the new array. Both the original array and the new array refer to the same object. That is, if the referenced object is modified, the change is visible to both the new array and the original array. This includes elements that are also array parameters of arrays. - Data types such as string, number and Boolean (not
String
,Number
andBoolean
) objects):concat
the string and number values to the new array.
- Object reference (not actual object):
let arr1 = [1,2,3]
let arr2 = [4,5,6]
let arr3 = [[1,2],[3,4]]
console.log(arr1.concat(arr2));
//[ 1, 2, 3, 4, 5, 6 ]
// 嵌套合并
console.log(arr1.concat(arr2).concat(arr3));
// [ 1, 2, 3, 4, 5, 6, [ 1, 2 ], [ 3, 4 ] ]
let obj1 = [{a:1},{b:2}]
let obj2 = [{c:3},{d:4}]
let obj3 = obj1.concat(obj2)
console.log(obj3);
//[ { a: 1 }, { b: 2 }, { c: 3 }, { d: 4 } ]
obj1[0].a = 4 //改变obj[0]对象值,会直接影响合并后的数组,因为是浅拷贝
console.log(obj3);
//[ { a: 4 }, { b: 2 }, { c: 3 }, { d: 4 } ]
toString()
toString()
returns a string representing the specified array and its elements.
When an array is used as a text value or string concatenation operation, it will automatically call its toString
method.
For array objects, the toString
method concatenates the arrays and returns a string containing each array element separated by a comma.
Syntax
arr.toString()
const arr = [1,2,3]
console.log(arr.toString()); //1,2,3
join()
join()
method returns a string by concatenating array elements separated by a comma or a specified delimiter string.
If the array has only one item, the item will be returned without using a separator.
Syntax
join()
join(separator)
separator
: Specified split character <font style="color:red">optional</font>
const arr = ['2021','08','08']
console.log(arr.join()); //2021,08,08
console.log(arr.join('-')); //2021-08-08
console.log(arr.join('/')); //2021/08/08
slice()
slice()
method returns a new array object, that the object is a begin
and end
original array decision shallow copy (including begin
, not including end
). The original array will not be changed.
Syntax
arr.slice(begin, end)
begin
: Specify the intercepted start index <font style="color:red">optional</font>- Start from 0 by default
- If
begin
is a negative number, the second element from the end ofslice(-2)
will be truncated from the absolute value from the end of the array - If
begin
exceeds the index range of the original array, an empty array will be returned.
end
: Specify the intercepted end index <font style="color:red">optional</font>- If
end
is omitted,slice
will be extracted to the end of the original array. - If
end
greater than the length of the array,slice
will also be extracted to the end of the original array. - If
end
is a negative number, it means that the last element in the original array has been extracted.
- If
const arr = [11,22,33,44,55,66,77,88]
console.log(arr.slice(1,4));
// 应该返回 索引 1 - 3 的数组元素
// [ 22, 33, 44 ]
console.log(arr.slice(-4,2)) //[]
console.log(arr.slice(-4)); //[ 55, 66, 77, 88 ]
console.log(arr.slice(0,-1));
// [
// 11, 22, 33, 44,
// 55, 66, 77
// ]
references
Previous wonderful articles
- 8 ways of Vue component communication
- Vue3 + TypeScript development practice summary
- Vue permission routing + data permission best practices
at last
The article has spent a week after get off work, and writing is not easy. The content in the article refers to the MDN document.
If you like it, you can like it 👍👍👍Follow and support, I hope everyone can gain something after reading this article!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。