Home > Web Front-end > JS Tutorial > body text

Comprehensive analysis of Javascript array methods

小云云
Release: 2018-01-29 13:18:52
Original
1578 people have browsed it

This article mainly shares Javascript array methods with you, hoping to help you understand Javascript arrays better.

Full analysis of Javascript array methods (including es6)

1. Arrays have their own attributes

<span style="font-size: 14px;"> constructor //返回创建数组对象的原型函数<br> length //返回数组对象的长度<br> prototype //这个是老熟人了,可以增加数组的原型方法和属性,这个放在后面的继承中讲<br></span>
Copy after login

2. Array methods

<span style="font-size: 14px;">//首先让我们看看数组的对象属性。<br>Array.prototype<br></span>
Copy after login

Comprehensive analysis of Javascript array methods

1. concat

<span style="font-size: 14px;">用法:用来连接多个数组的方法<br>有了这个方法之后我们连接多个数组就方便了<br>array1.concat(array2,array3,...,arrayX) 该参数可以是一个具体的值也可以是数组对象<br></span>
Copy after login
<span style="font-size: 14px;">let arr = [];<br>let arr1 = [1,2,3,4,5,6];<br>let pos = 7;<br>console.log(arr.concat(arr1,pos)); // =>[1,2,3,4,5,6,7]<br><br>//ok 我们再看一个厉害的,合并一维数组和二维数组<br>var num1 = [[1]];<br>var num2 = [2, [3]];<br><br>var nums = num1.concat(num2); <br><br>console.log(nums); // =>[[1], 2, [3]] <br>console.log(nums[0][0]); // =>1<br></span>
Copy after login

2. copyWithin()
Usage: Shallow copy a part of the array to another location in the same array and return it without modifying its size
The point is not to change the size

<span style="font-size: 14px;">arr.copyWithin(target)<br><br>arr.copyWithin(target, start)<br><br>arr.copyWithin(target, start, end)<br><br>arr.copyWithin(目标索引, [源开始索引], [结束源索引])<br></span>
Copy after login

target (Required) 0 is the index of the base. If target is a negative number, then target is length+target
start (optional) 0 is the index of the base. If start is a negative number, then start is length+start. If it is omitted, it is 0.
end(optional) 0 is the index of the base. If end is a negative number, then end is length+end. If it is omitted, it is arr.length
start=>end. In mathematics, it is [). For example, (0, 2) means to choose subscript 0, 1 (1,4) means to choose subscript 1, 2, 3, and so on
Let’s look at a few examples

<span style="font-size: 14px;">[1, 2, 3, 4, 5].copyWithin(-2); <br>//=> [1,2,3,1,2] targer为-2,也可以等于-2+5=3 start和end省略 所以等同于copyWithin(3,0,5)<br><br>[1, 2, 3, 4, 5].copyWithin(0, 3); // => [4,5,3,4,5]<br><br>[1, 2, 3, 4, 5].copyWithin(0, 3, 4); //=> [4,2,3,4,5] <br><br>[1, 2, 3, 4, 5].copyWithin(-2, -3, -1); <br>//=>[1, 2, 3, 3, 4]  -2等同于-2+5=3 -3等同2 -1等同于4 所以等同于copyWithin(3,2,4)<br><br>//ok,我们再来看一个特殊的,copyWithin并不单单能对数组对象使用还能对类数组对象使用<br>[].copyWithin.call({length:5, 3:1},0,3); //=> {0:1,3:1, length:5}<br>/*为什么会出这么个玩意?别急待我一步一步和你说<br>{length:5, 3:1} => {0:undefined,1:undefined,2:undefined,3:1,4:undefined,length:5}<br>[].copyWithin => Array.prototype.copyWithin.call()这一步也就是把类数组能使用数组的copyWithin方法.<br>[].copyWithin.call({length:5, 3:1},0,3)=>[undefined,undefined,undefined,1,undefined].copyWithin(0,3)=>[1,undefined,undefined,1,undefined]=>{0:1,3:1, length:5}<br>*/<br></span>
Copy after login

3 . entries
Usage: array.entries(); Returns a new Array Iterator object that contains the key-value pair for each index in the array
Let’s look at a piece of code first:

<span style="font-size: 14px;">var arr= ['a','b','c'];<br><br>var Iterator = arr.entries(); //返回一个Array Iterator对象<br>console.log(Iterator.next().value); //=>[0:"a"]<br>console.log(Iterator.next().value); //=>[1:"b"]<br>console.log(Iterator.next().value); //=>[2:"c"]<br></span>
Copy after login

ok, after introducing the basic usage, let’s look at the specific application

<span style="font-size: 14px;">//二维数组排序<br>var arr = [[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];<br><br>function sortArr(arr){<br><br>    var pos = true;<br>    var Iteartor = arr.entries();<br><br>    while(pos){<br><br>        var result = Iteartor.next();<br>        if(result.done !== true){ //当循环到最后一个的时候result.done会变成true<br>             <br>             result.value[1].sort((a,b)=>a-b);<br><br>        }else{<br>             <br>             pos = false;<br>        }<br><br>    }<br><br>}<br><br>sortArr(arr);<br></span>
Copy after login

Let’s look at another one

<span style="font-size: 14px;">var arr = ['a','b','c'];<br>var iteartor = arr.entries();<br><br>for(let i of iteartor){<br>    console.log(i);<br>}<br><br>//[0, "a"]<br>//[1, "b"]<br>//[2, "c"]<br></span>
Copy after login

for. . of loop can traverse the iterator object // I will explain the details in a later article

4.Array.from
Usage: You can convert an array-like or iterable The object creates a new array (the original array will not be changed)
Let’s take a small example first

<span style="font-size: 14px;">Array.from('abc'); //=>['a','b','c']<br>Array.from({0:'a',1:'b',length:2}) //=> ['a','b']<br></span>
Copy after login

Next let’s look at a magical example. One line of code changes the Element deduplication

<span style="font-size: 14px;">Array.from(new Set([4,2,4,2,6,6,7,8])); //=>[4,2,6,7,8] <br></span>
Copy after login

5.every
every(callback[,thisArg])
Usage: Used to test whether each element in the array satisfies a certain rule
Test function parameters: (value, index, arr) are the value of the array, the index of the array and the array
Return value: Boolean true or false

<span style="font-size: 14px;">var arr = [1,3,5,12,50,6];<br>var flag = arr.every(chenckIsBig);<br>function chenckIsBig(ele,index,arr){<br>     return ele<20;<br/>}<br/>console.log(flag) //=>false<br></span>
Copy after login

6.some
some(callback[,thisArg])
Usage: Used to test whether any elements in the array meet certain rules
Test function parameters: (value, index, arr) respectively. The value of the array, the index of the array and the array
Return value: Boolean true or false

<span style="font-size: 14px;">var arr = [1,3,5,12,50,6];<br>var flag = arr.some(chenckIsBig);<br>function chenckIsBig(ele,index,arr){<br>     return ele<20;<br/>}<br/>console.log(flag) //=>true<br></span>
Copy after login

7.filter
filter(callback[,thisArg])
Usage: Used to create a new array that satisfies all functions that pass the parameter function test
Test function parameters: (value, index, arr) are the value of the array, the index of the array, and the array
Return value: Return a new array
Let’s look at a small example first

<span style="font-size: 14px;">const checkIsBigEnough = (value) => value >= 10<br>let arr = [6,12,50,77,95];<br>console.log(arr.filter(checkIsBigEnough)); //=> [12,50,77,95]<br></span>
Copy after login

ok, let me give you another example that I often use. Sometimes we get it through ajax The json data passed through the background, but not all data can be used by us. At this time, the filter becomes more important. Let’s look at the example

<span style="font-size: 14px;">//我从后台获取了一个数组,数组中包含多个对象如下:<br>let json = [<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"},<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"},<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"},<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"},<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"}<br>]<br>//这个时候我只需要获取FromStation值为北京的对象,这个时候filter就派上用场了<br>let filterMethod = (value) => value.FromStation == "北京"<br>let finallyData = json.filter(filterMethod);<br>console.log(finallyData);<br>//=> [{"CostTime": "336", "FromStation": "北京"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "336", "FromStation": "北京"}]<br></span>
Copy after login

8.find
find(callback[,thisArg])
Usage: Similar to the above ones, the usage is similar to filter, but the return value of find is the first value that matches the test function
Test function parameters: (value, index , arr) are respectively the value of the array, the index of the array and the array
Return value: the value of the first array that meets the test function, if there is no qualified value, Undefined

<br><span style="font-size: 14px;">    let json = [<br>    {"CostTime": "310", "FromStation": "上海"},<br>    {"CostTime": "336", "FromStation": "北京"},<br>    {"CostTime": "340", "FromStation": "杭州"},<br>    ]<br>    <br>    let checkMethod = (value) => value.CostTime == "340"<br>    <br>    console.log(json.find(checkMethod)); //=>{"CostTime": "340", "FromStation": "杭州"}<br></span>
Copy after login

9.findIndex
Usage: Similar to the above ones, the usage is similar to find, but the return value of findIndex is the index that matches the first value of the test function
Test function parameters: (value , index, arr) are respectively the value of the array, the index of the array and the array
Return value: the value of the first array that meets the test function, if there is no qualified value, -1
## is returned #

<span style="font-size: 14px;">let json = [<br>{"CostTime": "310", "FromStation": "上海"},<br>{"CostTime": "336", "FromStation": "北京"},<br>{"CostTime": "340", "FromStation": "杭州"},<br>]<br><br>let checkMethod = (value) => value.CostTime == "340"<br>let checkMethod2 = (value) => value.FromStation == "深圳"<br><br>console.log(json.findIndex(checkMethod)); //=>2<br><br>console.log(json.findIndex(checkMethod2)); //=> -1<br></span>
Copy after login

10.fillarr.fill(value)
arr.fill(value, start)
arr.fill(value, start, end)

Usage: Use a fixed value to fill all elements in the array from the actual index to the termination indexParameters:
value (required) The value used to fill the array
start (Optional) Starting index, the default value is 0. If it is a negative number, start = start+arr.length
end (Optional) End index, the default value is arr.length. If it is a negative number, end = end+arr. length
start=>end is [) in mathematics, select a value greater than or equal to start and less than end
Return value: modified array

<span style="font-size: 14px;">[1,2,3].fill(5) //=> [5,5,5] 不传start默认为0,不传end默认为arr.length<br>[1,2,3].fill(5,1) //=>[1,5,5] <br>[1,2,3].fill(5,1,2) //=>[1,5,3]<br>[1,2,3].fill(5,1,1) //=>[1,2,3] 不变因为大于等于1小于1的值没有<br>[1,2,3].fill(5,-3,-2) //=>[5,2,3] start = -3 => -3+3 = 0  end = -2 =>-2 + 3 = 1 =>fill(5,0,1)<br>Array(3).fill(5) //=> [5,5,5] 这个方法比较有用,可以初始化数组(将所有值初始化为一个值)<br></span>
Copy after login

11.indexOf
arr.indexOf(searchElement,formIndex)
参数:
searchElement要查找的元素
formIndex从哪开始查找 (formIndex为一个整数,可以为负数,当formIndex为负数的时候formIndex可以转化成formIndex+arr.length 如果还为负数的话表示查找整个元素)
返回值:-1(没有找到元素) 或者 元素的下标(找到元素)

<span style="font-size: 14px;">// 找出指定元素在数组中出现的位置<br>var positionIndex = [];<br>var arr = [1,5,6,1,7,8,1,6,6,6];<br>var pos = arr.indexOf(1);<br>while(pos!=-1){<br>   positionIndex.push(pos);<br>   pos = arr.indexOf(1,pos+1);<br>}<br>console.log(positionIndex); // => [0,3,6]<br></span>
Copy after login

12.reduce
用法:方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。(这个是mdn文档上写的,看起来感觉特别难懂,其实他就是一个将数组元素不断递归执行一个函数之后返回的值)
我们还是先看例子:

<span style="font-size: 14px;">//数组累加<br>var arr = [3,6,5,1];<br>arr.reduce((pre,cur)=>pre+cur,10) //10+3+6+5+1 => 25<br><br>//数组累乘<br>var arr = [3,6,5,1];<br>arr.reduce((pre,cur) => pre*cur) //3*6*5*1 =>90<br></span>
Copy after login

ok,我们先来看看reduce函数
reduce((preValue,curValue,index,array)=>{},initialValue)
我们先看回调函数中的值:
preValue: 上一次调用回调返回的值,或者是提供的初始值(initialValue)著作权归作者所有。
curValue: 数组中当前被处理的数组项
index: 当前数组项在数组中的索引值
array: 调用 reduce()方法的数组
我们写一个demo来看看这个方法是如果实行的

<span style="font-size: 14px;">let arr = [1,2,3,4,5,6,7];<br>arr.reduce((pre,cur)=>{<br>   console.log(pre,cur);<br>   return pre+cur;<br>})<br>/*<br>1,2<br>3,3<br>6,4<br>10,5<br>15,6<br>21,7<br>28<br>*/<br><br>arr.reduce((pre,cur)=>{<br>   console.log(pre,cur);<br>   return pre+cur;<br>},10)<br>/*<br>10,1<br>11,2<br>13,3<br>16,4<br>20,5<br>25,6<br>31,7<br>38<br>*/<br></span>
Copy after login

由此可以看出:

  1. 在initialValue没有传入的时候
      pre在第一次循环的时候为数组第一个数
      cur为数组第二个值

  2. 在initialValue有值的时候
      在第一次循环pre初始为initialValue
      cur为数组第一个值

其实reduce以递归的思想可以理解为:
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
再举一个reduce的常用例子吧,二维数组的合并

<span style="font-size: 14px;">var twoArr = [['a','b'],['c','d'],['e','f']];<br>twoArr.reduce((pre,cur)=>{<br>   return pre.concat(cur)<br>},[])<br>//=> a,b,c,d,e,f<br></span>
Copy after login

13.reduceRight
用法其实和reduce基本没有区别,唯一的区别是他是从右到左执行回调函数

<span style="font-size: 14px;">var twoArr = [['a','b'],['c','d'],['e','f']];<br>twoArr.reduceRight((pre,cur)=>{<br>   return pre.concat(cur)<br>},[])<br>//=> f,e,d,c,b,a<br></span>
Copy after login

let arr = [1,2,3,4,5,6];
arr.slice(0,2); // =>[1,2]
arr.slice(-1) // =>[6]
arr.slice(0) // => [1,2,3,4,5,6]
arr.slice(-7) //=> [1,2,3,4,5,6]
arr.slice(2,-3) // => [3]

字符串方法和数组方法相似
let str = 'I am Bob';
str.slice(-5); //=> m Bob
str.slice(0,6); //=> I am B

数组方法之splice
splice(start,deleteCount,item...)
用法:万精油方法,可以对数组进行增加,删除,插入,可以从数组中移除一个或者多个元素,并且用后面的item来替换它,返回值为删除的元素的数组,并且改方法会改变原数组
let arr = [1,2,3,4,5,6];
arr.splice(0,5); [1,2,3,4,5]返回一个呗删除的数组
console.log(arr); // =>[6]
arr.splice(0,0,7,8,9); //返回一个空数组[]
arr // =>[7,8,9,6]

数组的遍历

<span style="font-size: 14px;">let arr = [1,2,3,4];<br>//普通for循环<br>for(var i = 0,length=arr.length;i < length;i++){<br/>    //do someThing<br/>}<br/><br/>//forEach循环<br/>arr.forEach((value, index)=>{<br>   //do someThing<br>})<br><br>//map循环<br>arr.map((value, index)=>{<br>   //do someThing<br>})<br><br>//其实还有两个循环一个for in ,还有一个是for of,不过强烈介意不要用for in,一个是效率比普通for循环差好多,因为它会遍历整个数组的原型对象,我们来看一个例子<br>//我们给数组原型添加一个haha的方法<br>Array.prototype.haha = function(){<br>    //do somthing<br>}<br>//然后我们再用for in来输出数组<br>for(let i in arr){<br>    console.log(arr[i]);<br>}<br>//=> 1,2,3,4 haha<br>最后竟然输出了haha,这是因为for in这个循环会遍历数组的原型对象,所以会输出haha,那么要解决这个有方法么?其实也有:<br>for(let i in arr){<br>    if(arr.hasOwnProperty(i))<br>    console.log(arr[i]);<br>}<br>//可以看到遍历输出了正确的值,但是还是不建议大家使用for in去循环数组,不单单是效率低,而且容易出问题,特别是当项目引用了许多第三方类库的时候。<br>有大牛做过一个测速,遍历数组的时间对比 for in > map > forEach > for<br></span>
Copy after login

数组元素的添加和删除

  1. push 将一个或者多个数组添加到数组的末尾,并且返回数组的长度
      Array.prototype.push(ele1,ele2,ele3,ele4)

  2. pop 删除数组的最后一个值,并且返回删除元素的值
      Array.prototype.pop()

  3. shift删除数组第一个值,并且返回删除元素的值,用法和pop相似
      Array.prototype.shift()

  4. unshift 用法和push相似,将一个或者多个元素添加到数组的开头,并且返回数组的长度

    <span style="font-size: 14px;">Array.prototype.unshift(ele1,ele2,ele3,ele4)<br></span>
    Copy after login

数组和字符串之间的相互转化

  1. 数组转化成字符串
      join:首先join方法不会改变原数组,只会返回一个生成的新字符串

<span style="font-size: 14px;">let a = ['a','b','c'];<br><br>console.log(a.join()) //=> 'a,b,c'<br>console.log(a.join("")) //=> 'abc'<br>console.log(a.join('-')) //=> 'a-b-c'<br></span>
Copy after login

ok,这个比较简单,我们在来看一个复杂点的,类数组转化成字符串

<span style="font-size: 14px;">function f(a,b,c){<br>   let e = Array.prototype.join.call(arguments,"");<br>   console.log(e);<br>}<br>f('Hello',' ','World'); //=> Hello World<br></span>
Copy after login
  1. 字符串转化成数组

用字符串的split方法,具体先不多说,等写字符串方法全解析的时候再进行具体说明。

相关推荐:

几种javascript数组定义的方法详解

Summary of various common uses of JavaScript arrays

Summary of JavaScript array operations

The above is the detailed content of Comprehensive analysis of Javascript array methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!