日常分享——数组API分享

数组API分享

1. join()

数组单元素拼接成了字符串

let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
let str = arr.join('');
console.log(str);  //abcdef

   
   
  • 1
  • 2
  • 3
2. concat()

合并两个数组,生成新数组

let arr = [1, 2, 3];
let a = ['a', 'b', 'c'];
let b = [11, 22, 33];
let re = arr.concat(a, b, 'aa', 'bb', 'cc');
console.log(re);

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
3. sort()

对原数组单元值排序

let arr = [23, 123, 6, 9, 7];

// 正序排列:
let re = arr.sort( function (a, b) { return a - b; } );

// 倒序排列:
let re = arr.sort(function (a, b) { return b - a; });

4. forEach()

用于遍历数组,替代for循环

let arr=['张飞','赵云','张辽']
// forEach:遍历数组
arr.forEach( function(item,index,o){
    // 第一个参数:代表数组的每个元素,当前元素
   	// 第二个参数:代表数组的每个元素的索引值,当前项的索引值
	// 第三个参数:代表当前数组本身
    console.log(item,index,o)
})

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
5. revers()

反转数组顺序

let arr = [1, 2, 3];
let re = arr.reverse();
console.log(re);

 
 
  • 1
  • 2
  • 3
6. Array.from()

伪数组转成真数组

要想把伪数组转成真数组,必须有length属性

Array.from(转换的伪数组名)

 
 
  • 1
7. find()

用于查找首次满足条件的首次值,并返回

let re = [2, 4, 6, 9, 7, 8].find(function (item, index, o) {
    console.log(item, index, o)
    return item > 3
})
console.log(re)

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
8. findIndex()

查找首次满足条件的值,并返回索引值

let re = [2, 4, 6, 9, 7, 8].findIndex(function (item, index) {
    return item > 3
})
console.log(re)

 
 
  • 1
  • 2
  • 3
  • 4
9. some()

用于查找是否有满足条件的值,有就返回true,没有false(找到立即停止执行)

[2, 4, 6, 9, 7, 8].some(function (*item*, *index*) {

  return *item* > 3    //true

  return *item* > 100    //false

})

10. every()

用于查找元素满足条件,都满足返回true,没否则就是false

let re = [2, 4, 6, 9, 7, 8].every(function (item, index) {
    return item > 3   //false
})
console.log(re)

 
 
  • 1
  • 2
  • 3
  • 4
11. filter()

用于筛选满足条件的元素,把所有满足条件的元素放到新数组返回

[2, 4, 6, 9, 7, 8].filter(function (*item*, *index*) {

  return *item* % 2 === 0   //[2,4,6,8]

})

12. map()

用于遍历数组每个元素执行一遍回调函数,把所有结果放到新数组返回

let re = [2, 4, 6, 9, 7, 8].map(function (item, index) {
    return item * item   //[4,16,36,81,49,64]
})

 
 
  • 1
  • 2
  • 3
13. indexOf()

检索数组单元值(查找在数组中首次出现的索引位置)

  • 如果找到就会返回首次出现的位置,找不到就会返回-1
  • lastIndexOf:查找在数组中尾次出现的索引位置,找不到就是-1
let arr = ['a', 'b', 'c', 'd', 'a', 'b', 'c'];
// 如果找到就会返回首次出现的位置,找不到就会返回-1
// let re = arr.indexOf('b');
// lastIndexOf:查找在数组中尾次出现的索引位置,找不到就是-1
let re = arr.lastIndexOf('b');
console.log(re);

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
14. reduce()

数组求和,求乘积

var  arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值