vue 取数组中的元素_Vue中常用的数组方法

(1).filter()

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
是否改变原数组:否
是否对空数组进行检测:否

语法:

const arr= [32, 33, 16, 40];
const arr1 = arr.filter(item => item >= 18)
console.log(arr)   // [32, 33, 16, 40]
console.log(arr1)  // [32, 33, 40]

(2).map()

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
是否改变原数组:否
是否对空数组进行检测:否

语法:

const arr= [4, 9, 16, 25];
const arr1 = arr.map(item => item+2)
console.log(arr)   // [4, 9, 16, 25]
console.log(arr1)  // [6, 11, 18, 27]

(3).forEach()

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。注意: forEach() 对于空数组是不会执行回调函数的。tips: forEach()中不支持使用break(报错)和return(不能结束循环),有需要时可使用常规的for循环。

语法:

const arr= [4, 9, 16, 25];
const arr1 = [];
arr.forEach(item => arr1.push(item))
console.log(arr)   // [4, 9, 16, 25]
console.log(arr1)  // [4, 9, 16, 25]

(4).find()

find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。

find() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
  • 如果没有符合条件的元素返回 undefined

注意: find() 对于空数组,函数是不会执行的。注意: find() 并没有改变数组的原始值。

语法:

const arr= [4, 9, 16, 25];
const b = arr.find(item => item>10)
const c = arr.find(item => item<1)
console.log(arr)   // [4, 9, 16, 25]
console.log(b)  // 16
console.log(c)  // undefined

(5).findIndex()

findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

findIndex() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
  • 如果没有符合条件的元素返回 -1

注意: findIndex() 对于空数组,函数是不会执行的。注意: findIndex() 并没有改变数组的原始值。

语法:

const arr= [4, 9, 16, 25];
const b = arr.findIndex(item => item>10)
const c = arr.findIndex(item => item<1)
console.log(arr)   // [4, 9, 16, 25]
console.log(b)  // 2
console.log(c)  // -1

(6).some()

some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:

  • 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
  • 如果没有满足条件的元素,则返回false。

注意: some() 不会对空数组进行检测。注意: some() 不会改变原始数组。

语法:

const arr= [4, 9, 16, 25];
const b = arr.some(item => item>10)
const c = arr.some(item => item<1)
console.log(arr)   // [4, 9, 16, 25]
console.log(b)  // true
console.log(c)  // false

(7).every()

every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。
every() 方法使用指定函数检测数组中的所有元素:

  • 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
  • 如果所有元素都满足条件,则返回 true。

注意: every() 不会对空数组进行检测。注意: every() 不会改变原始数组。

语法:

const arr= [4, 9, 16, 25];
const b = arr.every(item => item>10)
const c = arr.every(item => item>1)
console.log(arr)   // [4, 9, 16, 25]
console.log(b)  // false
console.log(c)  // true
  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值