当前位置:   article > 正文

JS数组的方法大全_js数组方法

js数组方法

一、常用的数组方法

  • concat()    连接两个或更多的数组  返回新数组 不改变原数组
  1. var a = [1,2,3]
  2. var b = [4,5]
  3. var c = a.concat(b)
  4. console.log(a) // [1,2,3]
  5. console.log(b) // [4,5]
  6. console.log(c) // [1,2,3,4,5]
  • join()  把数组的所有元素放入一个字符串 元素通过指定的分隔符进行分隔 不改变原数组
  1. //不传参数默认是, 传参 把数组中每一个元素toString()然后拼接
  2. var a = [1,2,3]
  3. var b = a.join('*')
  4. console.log(a) // [1,2,3]
  5. console.log(b) // 1*2*3
  • pop()   删除并返回数组的最后一个元素 改变原数组
  1. var a = [1,2,3]
  2. var b = a.pop()
  3. console.log(a) // [1,2]
  4. console.log(b) // 3
  • push()  向数组的末尾添加一个或更多元素 返回新的长度  改变原数组
  1. var a = [1,2,3]
  2. var b = a.push(4)
  3. console.log(a) // [1,2,3,4]
  4. console.log(b) // 4
  •  shift() 删除并返回数组的第一个元素 改变原数组
  1. var a = [1,2,3]
  2. var b = a.shift()
  3. console.log(a) // [2,3]
  4. console.log(b) // 1
  •  unshift()   向数组的开头添加一个或更多元素 返回新的长度 改变原数组
  1. var a = [2,3]
  2. var b = a.unshift(1)
  3. console.log(a) // [1,2,3]
  4. console.log(b) // 3
  • reverse()   颠倒数组中元素的顺序 返回颠倒后的数组 会改变原数组
  1. var a = [1,2,3]
  2. var b=a.reverse()
  3. console.log(a) // [3,2,1]
  4. console.log(b) // [3,2,1]
  • sort()  对数组的元素进行排序 (按ASCII码) 返回排序后的数组  改变原数组
  1. var a = ['a','b','d','c']
  2. var b=a.sort()
  3. console.log(a) // ['a','b','c','d']
  4. console.log(b) // ['a','b','c','d']
  • slice() 从某个已有的数组返回选定的元素 返回新数组 不改变原数组
  1. //slice(start,end) 返回[start,end)之间的元素组成的数组
  2. var a = [1,2,3]
  3. var b = a.slice(0,1)
  4. var c = a.slice() // 不填参数默认剪切整个数组
  5. console.log(a) // [1,2,3]
  6. console.log(b) // [1]
  7. console.log(c) // [1,2,3]
  8. console.log(a===c) // false
  9. // 负数表示从后往前数
  10. var d = a.slice(-1,-2)
  11. console.log(d) // [] 从左向右截取,所以为[]
  12. var e = a.slice(-1)
  13. console.log(e) // [3]
  • splice()    对数组进行删除修改 返回被删除的元素组成的数组 改变原数组
  1. //splice(index,length,n1,n2....,nn) 表示从index开始删除length个元素,并从index开始新增元素n1~nn,放回被删除的元素组成的数组
  2. var a = [1,2,3]
  3. var b = a.splice(1,2,2,[3,4],5)
  4. console.log(a) // [1,2,[3,4],5]
  5. console.log(b) // [2,3]
  • toString()  把数组转换为字符串,并返回结果
  1. var a=[1,2,3]
  2. var b=a.toString()
  3. console.log(b) //1,2,3
  • toLocaleString()    把数组转换为本地字符串 并返回结果
  1. var a=[1,2,3]
  2. var b=a.toLocaleString()
  3. console.log(b) //1,2,3
  • valueOf()   返回数组对象的原始值
  1. var a=[1,2,3]
  2. var b=arr.valueOf()
  3. console.log(b) //[1, 2, 3]

二、ES5新增的数组方法

  • indexOf()  查找某元素在数组中的位置 存在则返回第一个位置的下标 否则返回-1
  1. var a = [1,2,3
  2. var b = a.indexOf(1)
  3. var c = a.indexOf(3,3) //第二个参数表示从哪个位置开始查找某元素
  4. console.log(b)  // 0
  5. console.log(c) // -1
  • lastIndexOf  和indexOf()相似 区别在于从尾部向首部查询 不改变原数组
  1. var a = [1,2,3
  2. var b = a.lastIndexOf(1)
  3. console.log(b)  // 2

注:若不使用下标,则一般通过includes()方法代替indexOf()

  • filter() 返回数组中满足条件的元素组成的新数组 原数组不变 filter()的参数是一个方法
  1. var a = [1,2,3]
  2. //第一个参数为一个函数 有三个参数 current:当前值 index:当前值下标 array:这个数组对象
  3. var b = a.filter(function(current,index,array){
  4. return current < 2
  5. })
  6. console.log(a) // [1,2,3]
  7. console.log(b) // [1]
  • forEach() 遍历数组 为每个元素调用指定函数
  1. var a = [1,2,3]
  2. var b = a.forEach(function(el,index,arr){
  3. console.log(el,index,arr)
  4. })
  5. /*1 0 (3) [1, 2, 3]
  6. 2 1 (3) [1, 2, 3]
  7. 3 2 (3) [1, 2, 3]
  8. */
  • map() 调用的数组的每一个元素传递给指定的函数  返回一个新数组  不改变原数组
  1. var a = [1,2,3];
  2. var b = a.map(function(el){
  3. return el*el;
  4. });
  5. console.log(b); // [1,4,9]
  • every() 判断数组中每一项都是否满足条件 只有所有项都满足条件 才会返回true
  1. var a = [1,2,3];
  2. var b = a.every(function(x){
  3. return x>1;
  4. });
  5. console.log(b); // false
  • some() 判断数组中是否存在满足条件的项 只要有一项满足条件 就会返回true
  1. var a = [1,2,3];
  2. var b = a.some(function(x){
  3. return x>1;
  4. });
  5. console.log(b); // true
  • reduce()  两个参数:函数和递归的初始值 从数组的第一项开始 逐个遍历到最后
  1. //函数接收四个参数值:前一个值 当前值 索引 数组对象
  2. var a=[1,2,3];
  3. var b=a.reduce(function(a,b){
  4. return a+b;
  5. })
  6. console.log(b)//7
  • reduceRight()  与reduce()使用一样 从数组的最后一项开始 向前遍历到第一项

三、ES6新增的数组方法

 (一)数组创建

  • Array.of():将参数中所有值作为元素形成数组
  1. var re=Array.of(10)  //1个元素 取出来是10
  2. var rem=Array(10)   //10个空元素 取出来是undefined
  3. console.log(re,rem)
  4. /* [10] (10)
  5. 0: 10 [empty × 10]
  6. length: 1 length: 10
  7. */  
  8. var re=Array.of(10,20,30) //工厂创建
  9. console.log(re) //[10, 20, 30]
  • Array.from():将类数组对象或可迭代对象转化为数组
  1. // 参数为数组,返回与原数组一样的数组但不相等
  2. console.log(Array.from([1, 2])); // [1, 2]
  3. // 参数含空位
  4. console.log(Array.from([1, , 3])); // [1, undefined, 3]
  5. var arr=Array.from([1,2,3],function(el){
  6.   return el*2
  7. })
  8. console.log(arr) // [2,4,6]
  • 类数组对象:必须含有 length 属性,且元素属性名必须是数值或者可转换为数值的字符
  1. var arr = Array.from({
  2. 0: ''hello,
  3. 1: 'world',
  4. 2: 2022,
  5. length: 3
  6. });
  7. console.log(arr); // ['hello', 'world', 2022]
  8. // 没有 length 属性,则返回空数组
  9. var arr = Array.from({
  10. 0: ''hello,
  11. 1: 'world',
  12. 2: 2022,
  13. });
  14. console.log(arr); // []
  15. // 元素属性名不为数值且无法转换为数值,返回长度为 length 元素值为 undefined 的数组
  16. var arr = Array.from({
  17. a: 1,
  18. b: 2,
  19. length: 2
  20. });
  21. console.log(arr); // [undefined, undefined]

(二)转换可迭代对象

  • 转换map
  1. var map = new Map();
  2. map.set('key0', 'value0');
  3. map.set('key1', 'value1');
  4. console.log(Array.from(map)); // [['key0', 'value0'],['key1','value1']]
  • 转换set

  1. var arr = [1, 2, 3];
  2. var set = new Set(arr);
  3. console.log(Array.from(set)); // [1, 2, 3]
  • 转换字符串

  1. var str = 'abc';
  2. console.log(Array.from(str)); // ["a", "b", "c"]

二、扩展的方法

  • find():查找数组中符合条件的元素,若有多个符合条件的元素,则返回第一个元素 
  1. var arr=[10,20,30]
  2. var re= arr.find(function(el){
  3.  if(el>20){
  4.    return true
  5.  }
  6. })
  7. console.log(re)  //30

注:数组空位处理为 undefined 

  • findIndex():查找数组中符合条件的元素索引,有多个符合条件的元素时返回第一个元素索引
  1. var arr=[10,20,30]
  2. var re= arr.findIndex(function(el){
  3.  if(el>20){
  4.  return true
  5.  }
  6. })
  7. console.log(re) //2
  • includes():包含,数组是否包含指定值      
  1. var arr=[1,2,3,4,5]
  2. var re=arr.includes(4)
  3. console.log(re)  //返回布尔值 true
  • fill():填充,将一定范围索引的数组元素内容填充为单个指定的值

  1. //改变原数组 无参数范围时全部填充   
  2. var arr=[1,2,3,4]
  3. var re=arr.fill("hello")
  4. console.log(re,arr)  
  5. //打印 0: "hello" 1: "hello" 2: "hello" 3: "hello"  
  1. var arr=[{name:"hha",age:21},{name:"heie",age:28},{name:"xixi",age:14},{name:"oo",age:10}]
  2.         arr.map(function(el){
  3. if(el.age>=18){
  4. el.drink=true
  5. }
  6. })
  7. console.log(arr)
  • flat(): 降维 嵌套数组转一维数组       
  1. var arr=[[10,20],30,40,[50,60,[70,[100,200],80],90]]
  2. var arr2=arr.flat(2)
  3. console.log(arr2)
  4. /*
  5. 0: 10
  6. 1: 20
  7. 2: 30
  8. 3: 40
  9. 4: 50
  10. 5: 60
  11. 6: 70
  12. 7: (2) [100, 200]
  13. 8: 80
  14. 9: 90
  15. */

    案例:自己设计实现flat函数:(默认完全降维 count为降级级别)       

  1. Array.prototype.myflat=function(count=Infinity){
  2.   var arr=[]
  3.           for(i=0;i<this.length;i++){
  4.             if(this[i].constructor==Array&&count>0){
  5.                 var newarr=this[i].myflat(count-1)
  6.                 for(j=0;j<newarr.length;j++){
  7.                    arr.push(newarr[j])
  8.               }
  9.               }else{
  10.                   arr.push(this[i])
  11.               }
  12.             }
  13.         return arr
  14.   }
  15. var re2=arr.myflat(2)
  16. console.log(re2)
  17. /*
  18. 0: 10
  19. 1: 20
  20. 2: 50
  21. 3: 60
  22. 4: 70
  23. 5: (2) [100, 200]
  24. 6: 80
  25. */

遍历:

  • entrys():遍历键值对
  1. for(let [key, value] of ['a', 'b'].entries()){
  2.    console.log(key, value);
  3. }
  4. // 0 "a"
  5. // 1 "b"
  6. // 不使用 for... of 循环
  7. let entries = ['a', 'b'].entries();
  8. console.log(entries.next().value); // [0, "a"]
  9. console.log(entries.next().value); // [1, "b"]
  10. // 数组含空位
  11. console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]
  • keys():遍历键名
  1. for(let key of ['a', 'b'].keys()){
  2.    console.log(key);
  3. }
  4. // 0 1
  5. // 数组含空位
  6. console.log([...[,'a'].keys()]); // [0, 1]
  • values():遍历键值    

  1. for(let value of ['a', 'b'].values()){
  2.    console.log(value);
  3. }
  4. // "a" "b"
  5. // 数组含空位
  6. console.log([...[,'a'].values()]); // [undefined, "a"]

 案例:

  1. arr=[10,20,30]
  2. var re=arr.keys()
  3. for(let i of re){
  4. console.log(i)  //打印 0 1 2
  5. }
  6. console.log(re)   //Array Iterator {}
  7. var ree=arr.values()
  8. for(let i of ree){
  9. console.log(i)   //打印 10 20 30
  10. }

 三、扩展运算符(...)

  • 复制数组:

  1. var arr = [1, 2],
  2. arr1 = [...arr];
  3. console.log(arr1); // [1, 2]
  4. // 数组含空位
  5. var arr2 = [1, , 3],
  6. arr3 = [...arr2];
  7. console.log(arr3); [1, undefined, 3]
  1. var arr = [10, 20, 30]
  2. var arr1=[1,2,3]
  3. var arr2 = [...arr,...arr1]
  4. console.log(arr, arr2)

总结:

原数组改变的方法:push pop shift unshift reverse sort splice
不改变原数组的方法:concat map filter join every some indexOf slice forEach

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/476980
推荐阅读
相关标签
  

闽ICP备14008679号