当前位置:网站首页>Learning notes: what are the common array APIs that change the original array or do not change the original array?
Learning notes: what are the common array APIs that change the original array or do not change the original array?
2022-07-26 09:38:00 【Bean sprouts don't eat beans】
Reviewed the common use of arrays api, Practice some parameters and details that you may easily confuse or ignore ~
It's better to knock it out by yourself , It's no use just looking ~
First write the summary in front :
Change the operation of the original array :pop / push / shift / unshift / splice / reverse / sort
Do not change the operation of the original array :concat / filter / join / slice / reduce / findIndex / forEach / map
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Array common api</title>
</head>
<body>
<script> var commonArr = [1,2,3,4]; var strArr = ['apple','orange','purple','lemon'] var noArr = []; // concat: Merge array (>=2), It doesn't change the original array , Returns a new array ( Shallow copy ) var concatArr = commonArr.concat([5,6]); console.log(commonArr,concatArr) // [1,2,3,4] [1,2,3,4,5,6] //filter: Create a new array , It contains elements that pass the test , Elements that fail the test return []( Don't change the original array ) var filterArr = commonArr.filter(item=>item>2); var fitlterStrArr = strArr.filter((item,index)=>item.length>5) console.log(commonArr,filterArr,fitlterStrArr) // [1,2,3,4] [3,4] // find: Return the first element of successful test , No return undefined ( It doesn't change the original array ) var findElement1 = commonArr.find((item,index,arr)=>item>2,window); // 3 var findElement2 = commonArr.find(item=>item>4); // undefined console.log(findElement1,findElement2) // findIndex: Return the index of the first element of successful test , No return -1 ( It doesn't change the original array ) var findElementIndex = commonArr.findIndex((item,index)=>{
return item>1 && index>2}) console.log(commonArr,findElementIndex); // [1,2,3,4] 3 // : Execute the given function once for each element of the array , Return value undefined ( It doesn't change the original array ) const arraySparse = [1,2,3,,6]; var sparseResult = arraySparse.forEach((item,index)=>{
noArr.push(item + 1); }) console.log(sparseResult,noArr) // map: Returns a new array composed of the results of the callback function executed by each element of the original array ( It doesn't change the original array ) var mapArr = strArr.map((item,index)=>item.length<6); console.log(mapArr) // [true, false, false, true] console.log(commonArr.map(item=>item*2)) // [2 4 6 8] // indexOf: Returns the first index of a given element found in the array , Otherwise return to -1 ( It doesn't change the original array ) var findIndex1 = commonArr.indexOf(1); console.log(findIndex1) // 0 var findIndex3 = commonArr.indexOf(3,-1); // -1 Means to search from the first element at the end of the array console.log(findIndex3) // -1 var findIndex2 = commonArr.indexOf(2,-4); console.log(findIndex2); // 1 // join: Array to string , If the array is empty , Returns an empty string ( It doesn't change the original array ) const joinStr = strArr.join(); // join No delimiter , The default is comma console.log(joinStr,typeof joinStr) // apple,orange,purple,lemon string console.log(strArr.join(''),strArr); // appleorangepurplelemon ["apple", "orange", "purple", "lemon"] // Passing in a null character means that there is no separator between all elements // pop: Delete the last element of the array and return its value Change the original array console.log(commonArr.pop(),commonArr) // 4-- Delete value [1,2,3] // push: Add one or more elements to the end of the array , And return the new length of the array Change the original array console.log(commonArr.push(4,5),commonArr) // 5-- The length of the array [1, 2, 3, 4, 5] //shift: Delete the first element of the array and return the value of that element Change the original array If the array is empty , return undefined console.log(commonArr.shift(),commonArr) // 1-- Delete value [2, 3, 4, 5] // unshift: Add one or more elements to the beginning of the array , And return the new length of the array ( Modify the original array ). console.log(commonArr.unshift(0,9,1),commonArr) // 7--- The length of the array [0, 9, 1, 2, 3, 4, 5] // reduce: Execute reducer function ( Ascending ), And summarize the results into a single return value ( It doesn't change the original array ) // reducer( Accumulator , Current value , Current index , Source array ) Accumulator --- Cumulative callback return value // notes : If not provided initialValue,reduce From the index 1 Where we started callback Method , Skip the first index . Provided initialValue, From the index 0 Start var sum = commonArr.reduce((accu,curr,index,arr)=>{
return accu+curr; },10); console.log(sum,commonArr) // 34 // Convert a two-dimensional array to a one-dimensional array var faltArr = [1,[2,3],5]; // Use flattening directly It doesn't change the original array ) console.log((faltArr.flat())) // [1, 2, 3, 5] // Use reduce var faltArrResult=faltArr.reduce((accu,curr,index,arr)=>{
console.log(accu,curr) return accu.concat(curr) },[]); console.log(faltArrResult) // [1, 2, 3, 5] // slice: Returns a new array containing the extracted elements [begin,end), The original array does not change ( Shallow copy of the original array ) var sliceArr = (faltArrResult.slice(2,4)) console.log(sliceArr,faltArrResult) // [3, 5] [1, 2, 3, 5] sliceArr.push(99); console.log(sliceArr,faltArrResult) // [3, 5] [1, 2, 3, 5] Array Boolean values, etc. have no effect var objArr = [{
name:'aaa',age:12},{
name:'bbb',age:123},{
name:'ccc',age:1234}]; var sliseObj = objArr.slice(0,2); console.log(sliseObj,objArr) // [{name:'aaa',age:444},{name:'bbb',age:123}]; [{name:'aaa',age:444},{name:'bbb',age:123},{name:'ccc',age:1234}] sliseObj[0].age = 444; console.log(sliseObj,objArr) // [{name:'aaa',age:444},{name:'bbb',age:123}]; [{name:'aaa',age:444},{name:'bbb',age:123},{name:'ccc',age:1234}] // splice( Starting position , Delete a few elements , What elements are added ): Delete or replace existing elements or add new elements in place to modify the array , Returns an array of deleted elements . This method will change the original array var spliceArr = objArr.splice(0,2); console.log(spliceArr) // [{name:'aaa',age:444},{name:'bbb',age:123}] console.log(commonArr) // [0, 9, 1, 2, 3, 4, 5] // commonArr.splice(0,4,888); // console.log(commonArr) //[888,3,4,5] console.log(commonArr.splice(1,2)) // [9,1] console.log(commonArr) // [0, 2, 3, 4, 5] console.log(commonArr.splice(1,0,1)) // [] No deleted elements , Then return an empty array ( Here are the new elements ) console.log(commonArr) // [0, 1, 2, 3, 4, 5] // Change the operation of the original array :pop push shift unshift splice reverse( Inversion array ) sort </script>
</body>
</html>
-------------------------------- Split line -----------------------------------------------------------
Add a few more array exercises :
1. What does the following code output ?
["1","2","3"].map(parseInt)
The result is : 1 NaN NaN
The analysis is as follows :
["1","2","3"].map(parseInt) // parseInt This way of writing without parameters , By default, the current loop's (item,index)
// Its traversal process is equivalent to parseInt(1,0) // 1
// parseInt(2,1) // NaN
// parseInt(3,2) // NaN
The above code is equivalent to :
["1","2","3"].map((item,index)=>parseInt(item,index))// parseInt( The number , Hexadecimal number -- The default is 0 10 Base number 2 Express 2 Base number )
2. Several methods to realize array de duplication :
const arrs = [1,2,3,4,1,3,5,5,6,1,2,9];
// 1. Use indexOf: Returns the first index of a given element found in the array , Otherwise return to -1 ( It doesn't change the original array )
function unique1(arr){
if(!Array.isArray(arr))return;
var newArr = []; // Create a new array to receive different values
for(var i=0;i<arr.length;i++){
if(newArr.indexOf(arr[i]) === -1) {
// Look in the new array for arrs The value in , If not, put the current value push Enter new array , If there is, do nothing , Enter next cycle
newArr.push(arr[i])
}
}
return newArr;
}
console.log(unique1(arrs)) // [1, 2, 3, 4, 5, 6, 9] Both string arrays and numbers can be used , Special characters don't work
// 2.sort: Array sorting ( In ascending or descending order ) Can only be used for numbers
function unique2(arr) {
if(!Array.isArray(arr))return;
let sortArr = arr.sort((a,b)=>a-b); // Ascending
let newArr = [];
for(let i=0;i<sortArr.length;i++) {
// Comparison of adjacent elements
if(arr[i] != arr[i+1]) {
newArr.push(arr[i])
}
}
return newArr
}
console.log(unique2(arrs)) // [1, 2, 3, 4, 5, 6, 9]
// 3.splice( Starting position , Delete a few elements , What elements are added ): Delete or replace existing elements or add new elements in place to modify the array , Returns an array of deleted elements . This method will change the original array
function unique3(arr) {
if(!Array.isArray(arr))return;
// Cyclic element
for(let i=0;i<arr.length;i++) {
// Loop comparison value Delete duplicate elements i=0 i=1 i=2
for(let j = i+1;j<arr.length;) {
// j =1 j=2
if(arr[i] === arr[j]) {
arr.splice(j,1); // arr = [1,1,2]
} else {
j++ //j=3
}
}
}
return arr
}
console.log(unique3(arrs)) // [1, 2, 3, 4, 5, 6, 9]
// 4.includes: Whether the array contains a specific value
function unique4(arr) {
if(!Array.isArray(arr))return;
let newArr = [];
for(let i=0;i<arr.length;i++) {
if(!newArr.includes(arr[i])) {
newArr.push(arr[i])
}
}
return newArr
}
console.log((unique4(arrs))) // [1, 2, 3, 4, 5, 6, 9]
// 5.set Object allows you to store unique values of any type , Whether it's the original value or the object reference
function unique5(arr) {
// Use the constructor to Array To Set object
let newArr = new Set(arr);
return [...newArr] // Use ... Operator will Set transformation Array
}
console.log(unique5(arrs)) // [1, 2, 3, 4, 5, 6, 9]
3. The number of occurrences of each element in the array :
The solution is : Write the array elements as attributes of the new object , And set the attribute value of the new object to 1, If the attribute is repeated , Then attribute value +1
function showTime(arr) {
let obj= {
};
for(let i=0;i<arr.length;i++) {
let data = arr[i];
let count = obj[data]; // Write array values to object properties
if(count) {
obj[data] += 1; // repeat , Attribute value plus 1
} else {
obj[data] = 1;
}
}
return obj;
}
console.log(showTime([1,1,1,1,2,3,[1,2,1]])) // {1: 4, 2: 1, 3: 1}
边栏推荐
猜你喜欢
MySQL的逻辑架构
After attaching to the process, the breakpoint displays "currently will not hit the breakpoint, and no symbols have been loaded for this document"
MySql5.7.25源码安装记录
Drawing shadow error diagram with MATLAB
Jmeter配置元件之CSV数据文件设置
Fiddler packet capturing tool for mobile packet capturing
mysql5.7.25主从复制(单向)
Redis sentinel mode setup under Windows
搜索模块用例编写
Fiddler抓包工具之移动端抓包
随机推荐
2020-12-29
uni-app学习总结
“互联网+”时代的现代医学
mysql5.7.25主从复制(单向)
tabbarController的使用
Basic use of Arc GIS 2
[untitled]
微信小程序图片无法显示时显示默认图片
Simple pedestrian recognition code to 88% accuracy Zheng Zhedong preparation
(2) Hand eye calibration of face scanner and manipulator (eye out of hand: nine point calibration)
系统安装Serv-U后IIS出错提示:HRESULT:0x80070020
Double authentication of server and client
[MySQL] understand the important architecture of MySQL (I)
copyTo
Custom password input box, no rounded corners
OFDM Lecture 16 - OFDM
Gauss elimination solves the inverse of matrix (Gauss)
Force deduction brush questions, sum of three numbers
IIS error prompt after installing Serv-U: hresult:0x80070020
高斯消元求解矩阵的逆(gauss)