JavaScript之数组

数组

遍历

一般方法
const arr = [1,2,3,4,5]
for (let i = 0; i < arr.length; i++) {
    const element = arr[i];
    if(element===2){
        // break
        continue
    }
    console.log(element)
}
each方法

不能用break和continue

arr.forEach(function(item){
    if(item===2){
        // break
        // continue
    }
    console.log(item)
})
every方法
arr.every(function(item){
    if(item===2){
        return false
    }
    console.log(item)
    return true
})
for in

用于对象使用

for(let index in arr){
    if(index == 2){
        continue
    }
    console.log(index,arr[index])
}
for of(ES6)
for (let item of arr) {
  console.log(item)
}

伪数组

特性像数组
不能直接调用数组的方法

let args = [].slice.call(arguments)

特征

  1. 靠索引保存数据
  2. 有length属性
a = { 0: 'a', 1: 'b', length: 2 }

通过为数组创建数组

let array = Array.from({ length: 5 }, function () { return 1 })
console.log(array)

创建数组

 // Array.prototype.of
 let array = Array.of(1, 2, 3, 5, 5)
 console.log(array)
 // Array.prototype.fill
 let array = Array(5).fill(1)
 console.log(array)
 // Array.fill(value, start, end)
 console.log(array.fill(8, 2, 4))

查找数组

  • filter

    let array = [1, 2, 3, 4]
    let find = array.filter(function (item) {
      return item % 2 === 0
    })
    console.log(find)//返回数组
    
  • find 找到后就停止(ES6)

    let find = array.find(function (item) {
      return item % 2 === 0
    })
    console.log(find)//返回单个字符
    
  • findIndex 查找第一次的位置

    let find = array.findIndex(function (item) {
      return item % 2 === 0
    })
    console.log(find)//返回第一个位置
    
  • ES6 find 和 filter 的区别

    遇到个功能是要分类就想说在前端过滤,不要从查数据库的时候过滤了。然后就想说除了filter还有啥好用的
    发现有个find,测试一番之后发现

    const list = [{'name':'1',index:1},{'name':'2'},{'name':'1'}]
    let list2 = list.find(i=>i.name==='1') 
    
    let list3 = list.filter(i=>i.name==='1')
    
    console.log(list); // [ { name: '1', index: 1 }, { name: '2' }, { name: '1' } ]
    console.log(list2); // { name: '1', index: 1 }
    
    console.log(list3); // [ { name: '1', index: 1 }, { name: '1' } ]
    

    find 和 filter 都是不改变原数组的方法

    但是find只查出第一个符合条件的结果像例子里是直接返回了一个对象而不是数组!而filter返回全部结果仍然是数组。

  • 专栏:JavaScript:遍历

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值