当前位置:网站首页>Deep understanding of common methods of JS array
Deep understanding of common methods of JS array
2020-11-06 01:17:00 【:::::::】
Array as an important data type , Except for the basic pop、push、shift、unshift In addition to a few methods , There are a lot of practical methods that are also our essential skills .
Suppose we have a team of people , Here's the picture :
We need to sort or filter them ( Metaphors are sorted by height , Screening women, etc ), We can all operate through arrays .
notes : Here's more about how to use , For detailed methods, please refer to : Array | MDN
Take out some people
First we define the data with an array ( For the sake of simplicity , We don't have so much data ):
var aPerson = ['person1', 'person2', 'person3', 'person4', 'person5', 'person6']
slice
Now suppose we're going to take three people , We can use slice() Method to select three people , as follows :
var aP3 = aPerson.slice(1, 4); console.log(aPerson); // ['person1', 'person2', 'person3', 'person4', 'person5', 'person6'] console.log(aP3); // ["person2", "person3", "person4"]
This method returns a start to end ( Not including the end ) A portion of the selected array is shallowly copied to a new array object . The original array will not change .
Please refer to :slice
splice
We can also use it splice() Method to select , as follows :
var aPerson = ['person1', 'person2', 'person3', 'person4', 'person5', 'person6'] var aP3 = aPerson.splice(1, 3); console.log(aPerson); // ["person1", "person5", "person6"] console.log(aP3); // ["person2", "person3", "person4"]
This method changes the contents of the array by deleting existing elements or adding new elements . The original array will change .
about slice Come on ,splice Will be more powerful , The main difference lies in :
- slice Do not change the original array , and splice It will change.
- slice The second parameter of is the index value up to , and splice The number of intercepts to be intercepted
- splice It can also be used to add elements ,slice Do not place
Please refer to :splice
concat
Except to pull some people out of the line , We can also merge another team and this team into a new team , as follows :
var aPerson1 = ['person1', 'person2', 'person3', 'person4', 'person5', 'person6'] var aPerson2 = ['person7', 'person8', 'person9']; var aPerson3 = aPerson1.concat(aPerson2); console.log(aPerson3); // ["person1", "person2", "person3", "person4", "person5", "person6", "person7", "person8", "person9"]
concat() Method is used to merge two or more arrays . This method does not change the existing array , Instead, it returns a new array .
Please refer to :concat
Order of height and height
Now we define a set of data in terms of height , as follows :
var aHeight = ['170', '165', '178', '183', '168', '175', '173'];
reverse
We can use it directly reverse() Method to achieve reverse order , as follows :
aHeight.reverse(); console.log(aHeight); // ["173", "175", "168", "183", "178", "165", "170"]
This method is very simple , There are no parameters , Is to change the order of the array , The first element will be the last , The last one will be the first . In general, it is seldom used .
sort
Compared with reverse() Come on ,sort() There are more places to use the method . Let's start with a short to high order , as follows :
aHeight.sort(); console.log(aHeight); // ["165", "168", "170", "173", "175", "178", "183"]
sort() The default sort of method is ascending , The code above shows . But we can also pass in a function , Specify how it is sorted , For example, let it be arranged in descending order :
aHeight.sort(function(a, b){
return b - a;
});
console.log(aHeight); // ["183", "178", "175", "173", "170", "168", "165"]
Please refer to :sort
Stochastic ranking
In addition to the normal ascending and descending order , In fact, we often use random sorting , Such as our red envelope , Shuffling in chess and card games is an application of random sorting .
When using random sorting , We have to use a random function Math.random(). This function returns a floating point number , The numbers are in the range [0,1).
So we can use this randomly generated floating-point number with 0.5 Size comparison , That result may be greater than or less than 0, Finally, we get our random sort .
// First run
aHeight.sort(function(){
return 0.5 - Math.random();
});
console.log(aHeight); // ["183", "168", "175", "173", "170", "165", "178"]
// Second operation
aHeight.sort(function(){
return 0.5 - Math.random();
});
console.log(aHeight); // ["170", "183", "175", "168", "173", "165", "178"]
Because it's random , So every run is different , We can run it a few more times .
Conditional screening test
Now we define two sets of data in terms of skin color and age , as follows (yellow It means yellow people ,white It means white people ,black It means black people ):
var aColor = ['yellow', 'black', 'white', 'white', 'yellow', 'yellow']; var aAge = [19, 30, 25, 37, 18, 35];
Test for compliance
every
every() Method is used to test whether all the data of the array has passed the test of the specified function , If by returning true, otherwise false.
Metaphors judge whether all people are older than 20 year , as follows :
var ageTest = aAge.every(function(item, index){
return item > 20;
})
console.log(ageTest); // false
every If every data in the array satisfies this condition, it will return true, Otherwise, it would be false.
Please refer to :every
some
Corresponding every() Method , One more some() Method , Indicates that as long as any data in the array satisfies the condition, it will return ture, If none of the data is satisfied false.
To judge whether someone is older than 32 year , as follows :
var ageTest2 = aAge.some(function(item, index){
return item > 32;
})
console.log(ageTest2); // true
Please refer to :some
includes
includes() Method is used to determine whether the current array contains a specified value , If it is , Then return to true, Otherwise return to false.
To judge whether there is 35 A man of years old , as follows :
var ageTest3 = aAge.includes(35); var ageTest4 = aAge.includes(28); console.log(ageTest3); // true console.log(ageTest4); // false
Condition screening
filter
I want to choose all the yellow skin people , as follows :
var aYellow = aColor.filter(function(item, index) {
return item === 'yellow';
})
console.log(aYellow); // ["yellow", "yellow", "yellow"]
This method returns an array of data that satisfies the condition .
Please refer to :filter
Let everyone do something
forEach
forEach() Method to perform the provided function once for each element of the array , The method does not return a value .
It's a metaphor for everyone to get a red envelope from the boss during the festival , as follows :
var aPerson = ['person1', 'person2', 'person3', 'person4', 'person5', 'person6']
aPerson.forEach(function(item, index) {
console.log(item + ' Got 200 Yuan a red envelope ')
})
Please refer to :forEach
map
map() Method to create a new array , The result is that each element in the array calls a supplied function .
Everyone's salary is increased 5000 element , as follows :
// First, construct a salary data
var aSalary = [8000, 7000, 1500, 9000, 22000];
var aNewSalary = aSalary.map(function(item, index) {
return item + 5000;
})
console.log(aNewSalary); // [13000, 12000, 6500, 14000, 27000]
Please refer to :map
other
In addition to the methods mentioned above , There are also some common methods , Such as indexOf、join wait , I will not explain it here , For details, please refer to : Array | MDN
All in all , The array method must be familiar with , If you really can't remember , You have to know that there is such a thing , I know how to look it up later , Because we need these methods to deal with data when doing business .
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
- PHPSHE 短信插件说明
- 快快使用ModelArts,零基础小白也能玩转AI!
- Skywalking series blog 2-skywalking using
- 哇,ElasticSearch多字段权重排序居然可以这么玩
- Menu permission control configuration of hub plug-in for azure Devops extension
- 熬夜总结了报表自动化、数据可视化和挖掘的要点,和你想的不一样
- 多机器人行情共享解决方案
- 制造和新的自动化技术是什么?
- 一时技痒,撸了个动态线程池,源码放Github了
- 恕我直言,我也是才知道ElasticSearch条件更新是这么玩的
猜你喜欢

PHP应用对接Justswap专用开发包【JustSwap.PHP】

全球疫情加速互联网企业转型,区块链会是解药吗?

容联完成1.25亿美元F轮融资

哇,ElasticSearch多字段权重排序居然可以这么玩

大数据应用的重要性体现在方方面面

Computer TCP / IP interview 10 even asked, how many can you withstand?

Don't go! Here is a note: picture and text to explain AQS, let's have a look at the source code of AQS (long text)

中国提出的AI方法影响越来越大,天大等从大量文献中挖掘AI发展规律

熬夜总结了报表自动化、数据可视化和挖掘的要点,和你想的不一样

制造和新的自动化技术是什么?
随机推荐
iptables基礎原理和使用簡介
ipfs正舵者Filecoin落地正当时 FIL币价格破千来了
Python自动化测试学习哪些知识?
網路程式設計NIO:BIO和NIO
Analysis of ThreadLocal principle
使用NLP和ML来提取和构造Web数据
Leetcode's ransom letter
Grouping operation aligned with specified datum
Polkadot series (2) -- detailed explanation of mixed consensus
50 + open source projects are officially assembled, and millions of developers are voting
Cocos Creator 原始碼解讀:引擎啟動與主迴圈
事半功倍:在没有机柜的情况下实现自动化
业内首发车道级导航背后——详解高精定位技术演进与场景应用
【快速因數分解】Pollard's Rho 演算法
分布式ID生成服务,真的有必要搞一个
采购供应商系统是什么?采购供应商管理平台解决方案
基於MVC的RESTFul風格API實戰
Jmeter——ForEach Controller&Loop Controller
选择站群服务器的有哪些标准呢?
多机器人行情共享解决方案