当前位置:网站首页>Array method
Array method
2022-06-28 04:16:00 【weixin_ forty-seven million one hundred and sixty-four thousand】
.ES5 Array methods
1.Array.isArray()
Used to determine whether it is an array , Can make up typeof Lack of operators
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
var arrObj = {
};
console.log(Array.isArray(arr));//true
console.log(Array.isArray(arrObj));//false
2.valueOf()
Returns the original value of the array ( In general, it is the array itself )
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.valueOf());//[1, 3, 5, "xiaoming", "liuqiao"];
// It is judged that the array itself is returned
console.log(arr.valueOf()===arr) //true
3.toString()
Returns the string form of an array
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.toString());//1,3,5,xiaoming,liuqiao
4.indexOf()
Returns the first occurrence of the specified element in the array , No return -1
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.indexOf('xiaoming'));// Returns the index 3
5.lastIndexOf()
Returns the last position of the specified element in the array , No return -1
var arr = [1, 3, 5, "xiaoming", "liuqiao",'xiaoming'];
console.log(arr.lastIndexOf('xiaoming'));// Returns the index 5
6.push()
Used to add one or more elements to the end of the array , And return the array length after adding elements , Will change the original array of elements
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.push('xiaohong', 'xiaobai')); // Return array length 7
console.log(arr);// [1, 3, 5, "xiaoming", "liuqiao", "xiaohong", "xiaobai"]
7.pop()
Used to delete the last element of the array , And return the element , It's going to change the array
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.pop('liuqiao'))//liuqiao
console.log(arr);// [1, 3, 5, "xiaoming"]
8.join()
Take a string parameter as the separator , All elements of the array , Form a string and return , If there is no reference , Is separated by commas by default
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
console.log(arr.join('-'));//1-3-5-xiaoming-liuqiao
console.log(arr.join());//1,3,5,xiaoming,liuqiao
9.concat()
For merging multiple arrays , The elements of the new array , Add to the back of the original array element , Returns a new array , The original array remains the same
var arr = [1, 3, 5, "xiaoming", "liuqiao"];
var newArr = ['xiaohong', 'xiaobai']
console.log(arr.concat(newArr));//[1, 3, 5, "xiaoming",
console.log(arr);//[1, 3, 5, "xiaoming", "liuqiao"];
---------------------------------- Separator -----------------------------------
// Merge multiple arrays
var newArr = ['xiaohong']
var newArr2 = [2];
var newArr3= [6];
console.log(arr.concat(newArr,newArr2,newArr3));//[1, 3, 5, "xiaoming", "liuqiao", "xiaohong",2,6]
10.shift()
Used to delete the first element of an array , And return the element . It's going to change the array
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.shift());//xiaoming
console.log(arr);//[3, 5, 1, "liuqiao"]
11.unshift()
Used to add an element in the first position of the array , And return the array length after adding the new element . It's going to change the array
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.unshift('abc'));//6
console.log(arr);//["abc", "xiaoming", 3, 5, 1, "liuqiao"]
12.reverse()
Used to invert the order of elements in an array , Return the changed array . It's going to change the array
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.reverse());//["liuqiao", 1, 5, 3, "xiaoming"]
console.log(arr);//["liuqiao", 1, 5, 3, "xiaoming"]
13.slice()
Copy a part from the array , Return a new array , It also plays the same role in strings
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
// The inclusion index is 1 The elements of , The index is not included 3 The elements of ( The copy index is 1 2 The elements of )
console.log(arr.slice(1,3));//[3, 5]
console.log(arr);//["xiaoming", 3, 5, 1, "liuqiao"];
14.splice() The most advanced method
The array can be incremented 、 Delete 、 Change . Return is added , Deleted or modified elements , In the form of an array , It's going to change the array
Delete :splice When a parameter : Deleted starting index , Delete all until the end , Returns the deleted item
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.splice(2));//[5, 1, "liuqiao"]
console.log(arr); //["xiaoming", 3]
Delete : splice For two parameters : The first parameter is the starting index to be deleted , The second parameter is the number of items to delete Returns the deleted item
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.splice(0,2));//["xiaoming", 3]
console.log(arr); //[5, 1, "liuqiao"]
add to : splice: When there are three parameters : First starting position index ( That is, where to add ), The second parameter is 0, The third parameter is the inserted item . Return an empty array
// Generally speaking, it means : Where is it , Which items to add
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.splice(1, 0, 'xiaofang'));//[]
console.log(arr); //["xiaoming", "xiaofang", 3, 5, 1, "liuqiao"]
Replace :splice: Insert any item element into the array at the specified position , Delete any number of items at the same time
Three parameters : The first parameter : Start index position , The second parameter : Number of items deleted , The third parameter : Insert any number of items
Returns the deleted item
var arr = ["xiaoming", 3, 5, 1, "liuqiao"];
console.log(arr.splice(1, 2, 'xiaofang','xiaohong'));//[3,5]
console.log(arr);//["xiaoming", "xiaofang", "xiaohong", 1, "liuqiao"]
15.sort()
Sort the array , Returns an array of Sort by character encoding by default ( The default is ascending ) It's going to change the array
sort Sorting is the sorting of characters , First use the... Of the array toString() Method to string , Compare them bit by bit ,3 It is greater than 12 Of , Because the ending 3>1, So try not to use Number Sort data of type
When comparing strings , The first letter of English is passed ASCII The code can be converted to the corresponding value , Then compare according to the numerical value
var arr = ["xiaoming", 3, 5, 1, 12,"liuqiao"];
console.log(arr.sort());//["xiaoming", 3, 5, 1, 12,"liuqiao"];
console.log(arr);//["xiaoming", 3, 5, 1, 12,"liuqiao"];
Array sort method , You need to define your own callback function sort([fn]), Returns an array of
Ascending , Only numeric values can be sorted
var arr = [3, 5, 1, 12];
// Ascending , Only numeric values can be sorted
arr.sort(function (a, b) {
return a - b;// The first minus the second
});
console.log(arr);//[1, 3, 5, 12]
Descending , Only numeric values can be sorted
var arr = [3, 5, 1, 12];
// Descending , Only numeric values can be sorted
arr.sort(function (a, b) {
return b - a;// The second minus the first
});
console.log(arr);//[12, 5, 3, 1]
Custom sort function Ascending
var arr = [3, 5, 1, 12];
arr.sort(function (a, b) {
// Ascending
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
});
console.log(arr);//[1, 3, 5, 12]
16 some()
Determine whether there are items in the array that meet the conditions , As long as one of the conditions is met , It will return true,array.some(callback(value,index,self))some() Receive a callback function as an argument , This callback function needs to have a return value ,callback(value,index,self) There are three parameters
var arr = ["xiaoming", 3, 5, 1, 12, "liuqiao"];
// Equivalent to loop traversal
var bol = arr.some(function (value, index, self) {
console.log(value);// Traversal value
console.log(index);// Indexes
console.log(self);//self Express oneself
return value == 3;
});
console.log(bol);//true
You can determine whether a value exists , Or whether the conditions are met
some Implementation principle of : Because to judge every item in the array , As long as there is a callback function that returns true,some Will return to true, So with every Just the opposite , When a callback function is encountered, the return value is true when , Can determine the result , Then stop executing , After all, the data will not be traversed , Stop at the first return true The location of ; When the return value of the callback function is false when , Need to continue backward , It's not until the end that the result can be determined , So it will traverse all the data , The implementation is similar to forEach The function of , Traverse all of .
17.every()
Determine whether each item in the array satisfies the given condition , When all items meet the conditions , Will return true And some contrary
var arr = ["xiaoming", 3, 5, 1, 12, "liuqiao"];
var bol = arr.every(function (value, index, self) {
console.log(value);// Traversal value
console.log(index);// Indexes
console.log(self);//self Express oneself
return value == 3;
});
console.log(bol);//false
every And some Almost. , It's also loop traversal , As long as the conditions are not met , Stop immediately , return false
18.flat()
flat() Method recursively traverses the array at a specified depth , And all the elements and the elements in the traversed sub array are merged into a new array to return .
It has a parameter , Specifies the depth of the structure to extract the nested array , The default value is 1. in addition : Use Infinity, Can expand any depth of nested array
var arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
// Flatten an array
arr = arr.flat(Infinity);
// Use Set characteristic , You can get rid of it
arr = Array.from(new Set(arr));
console.log(arr);
// If you need to sort , You need to define your own callback function sort([fn]), Returns an array of
Two .ES6 Array methods
1. Extension operator …
1.1 Convert an array to a comma separated sequence of parameters
effect : Function call
var arr = [7, 8];
function sum(a, b) {
return a + b;
}
onsole.log(sum(...arr));//15
12345
1.2 For maximum
var arr = [7, 8, 20];
console.log(Math.max(...arr));//20
12
1.3 Mosaic array
var arr1= [7, 8, 20];
var arr2=["xiaoming",25];
arr1.push(...arr2);
console.log(arr1);//[7, 8, 20, "xiaoming", 25]
1234
1.4 Deep copy array
var arr1 = [1,2,3]
var arr2 = [...arr1]
console.log(arr1) // [1, 2, 3]
console.log(arr2) // [1, 2, 3]
arr2[0]=0
console.log(arr1) // [1, 2, 3]
console.log(arr2) //[0, 2, 3]
12345678
1.5 Merge multiple arrays ( Shallow copy )
var arr1 = ['1', '2'];
const arr2 = ['3'];
const arr3 = ['4', '5'];
var arr4=[...arr1, ...arr2, ...arr3]
console.log(arr4)// ["1", "2", "3", "4", "5"]
12345
1.6 Convert string to array
var msg=' I'm Chinese ';
console.log([...msg]);//[" I ", " yes ", " in ", " countries ", " people "]
- Array.of()
Used to put a set of values , Convert to array .
var arr = Array.of(“xiaoming”, 4, 7, 9);
console.log(arr);//[“xiaoming”, 4, 7, 9]
12 - Array.from()
ES6 by Array Added from Functions are used to convert other objects into arrays . Other objects have requirements : You can turn two objects into arrays 1. Deployed iterator Object of the interface , such as :Set,Map,Array2. Class array object , What is a class array object , It means that an object must have length attribute , No, length attribute , The result is an empty array . The class array objects you will encounter are : Function arguments keyword , Or a DOM aggregate .
3.1 Convert class array objects
var arr = {
'0': 10, '1': 15, length: 2 };
var array = Array.from(arr);
console.log(array);//[10, 15]
123
3.2 from string Generate an array in
var msg = " I'm Chinese ";
var arr=Array.from(msg)
console.log(arr);//[" I ", " yes ", " in ", " countries ", " people "]
123
3.3 from Set Generating arrays ( It can be used as a solution for array de duplication )
var set=new Set(['abc','foo','abc','cde']);
var arr=Array.from(set);
console.log(arr);// ["abc", "foo", "cde"]
// One line of code , Array weight removal
var arr1 = [1,2,4,2,3,5,1,3];
var arr2 = Array.from(new Set(arr1));
console.log(arr2);// [1, 2, 4, 3, 5]
12345678
3.4 Can traverse array , Data processing
var arr = ["xiaoming", 3, 5, 1, 12, "liuqiao"];
arr=Array.from(arr,item=>{
return item+"_hello";
});
console.log(arr);//["xiaoming_hello", "3_hello", "5_hello", "1_hello", "12_hello", "liuqiao_hello"]
4.fill()
fill() function , Fill the array with the specified elements , In fact, it initializes the three parameters of the array with the default contents : first : The filled element value is the second : Where to start filling ( Location index ) Third : End before where
var arr = [2, 5, 1, 12, 8];
// A value is filled in
arr.fill("liuqiao");
console.log(arr);//["liuqiao", "liuqiao", "liuqiao", "liuqiao", "liuqiao"]
//2 When you get a value , So let's start here , All filled
arr.fill("liuqiao",2);
console.log(arr);//[2, 5, "liuqiao", "liuqiao", "liuqiao"]
// Three values , Go to the index , From where to where before
arr.fill("liuqiao",0,2);
console.log(arr);//["liuqiao", "liuqiao", 1, 12, 8]
123456789101112
5.includes()
includes() Method is used to determine whether an array contains a specified value , According to the circumstances , Return if included true, Otherwise return to false.
var arr = ["xiaobin", 3, 5, 1, 12, "liuqiao"];
onsole.log( arr.includes("liuqiao"));//true
3、 ... and . Common iterative methods ( contain ES5 and ES6)
1.map
map() mapping , Run the given function for each item in the array , Returns an array of the results of each function call .
var arr = ["xiaobin", 3, 5, 1, 12, "liuqiao"];
//currentValue Items currently traversed
//index Item index
//array Current array
let array = arr.map(function (currentValue, index, array) {
return currentValue + 'hello';
});
console.log(array);//["xiaobinhello", "3hello", "5hello", "1hello", "12hello", "liuqiaohello"]
12345678
2.filter
filter() Filter , Run the given function for each item in the array , Return the data that meets the filter conditions
var arr = [3, 5, 1, 12, 8];
//currentValue Items currently traversed
//index Item index
//array Current array
var array=arr.filter(function (currentValue, index, array) {
return currentValue > 5;
});
console.log(array);//[12, 8]
12345678
3.forEach
forEach(), Loop through the array , Run the given function for each item in the array . This method does not return a value . And map Same function , But the difference is :forEach() Iterate through a method , But there is no return value ,map() Iterate through a method , There is a return value
var arr = ["xiaoming", 3, 5, 1, 12, "liuqiao"];
//item Items currently traversed
//index Item index
//array Current array
arr.forEach((item,index,array )=> {
// Perform a function
});
1234567
4.find()
To find the first qualified member of the array , Its argument is a callback function , All members execute the callback function in turn . Until you find out that the first return value is true Members of , Then return to the member . If there are no qualified members, return undefined
var arr = [3, 5, 1, 12, 8];
var array = arr.find(item => {
return item > 5
});
console.log(array);//12
var array = arr.find(item => {
return item > 12
});
console.log(array);//undefined
12345678910
5.findIndex()
findIndex() Method usage and find The method is very similar , Returns the location of the first qualified array member , If all members do not meet the criteria , Then return to -1
var arr = [2, 5, 1, 12, 8];
var index = arr.findIndex(item => {
return item > 5
});
console.log(index);//3
var index = arr.findIndex(item => {
return item > 13
});
console.log(index);//-1
边栏推荐
- Pinda general permission system (day 5~day 6)
- Simple factory mode
- 阿里P8倾情推荐,Fiddler抓包工具实战篇(一)
- Introduction notes to machine learning
- Uncertainty principle
- Genicam gentl standard ver1.5 (2)
- Talking about cloud primitiveness, we have to talk about containers
- ELK 搭建日志分析系统 + Zipkin服务链路追踪整合
- 短视频平台开发,点击链接、图片自动跳转到新的页面
- English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions
猜你喜欢

领歌leangoo敏捷看板工具新增导出卡片文档和粘贴共享脑图节点功能

Staggered and permutation combination formula

Iso8191 test is mentioned in as 3744.1. Are the two tests the same?

Meichuang data security management platform has obtained the evaluation certificate of "data security product capability verification plan" of the Institute

In the era of video explosion, who is supporting the high-speed operation of video ecological network?

Analysis of future teacher research ability under steam education framework

Introduction notes to machine learning

成长一夏 挑战赛来袭 | 学习、创作两大赛道,开启导师报名啦!

English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions

第一个.net core MVC项目
随机推荐
Learning about DC-DC step-down chip of sy8120i (12V reduced to 3.3V)
2022年中国音频市场年度综合分析
Uncover the mystery of SSL and learn how to protect data with SSL
短视频平台开发,点击链接、图片自动跳转到新的页面
Pychart shares third-party modules among different projects
Reading notes of top performance version 2 (II) -- CPU monitoring
Open the field of maker education and creation
AS 3744.1标准中提及ISO8191测试,两者测试一样吗?
内卷、躺平与中年危机的相关思考
Another option for ERP upgrade, MES system
Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"
Staggered and permutation combination formula
猫狗队列的问题
Notes to friendship chain
设计一个有getMin功能的栈
01 overview, application scenarios, Download methods, connection methods and development history of mongodb
[MySQL] multi table connection query
机器学习入门笔记
Digital promising, easy to reach, Huawei accelerates the layout of the commercial market with "five pole" star products
Une seule pile dans l'ordre inverse avec des fonctions récursives et des opérations de pile