当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ECMAScript 6中数组新方法

ECMAScript 6中数组新方法

2019年02月20日  | 移动技术网IT编程  | 我要评论
数组的方法 数组的的大部分方法都可以实现数组的遍历。 foreach方法 实现数组的遍历 map方法 map方法的作用:会生成一个与遍历对象数组相同长度的新数组,并且map中的返回值就是新数组的参数值。 filter方法 过滤,起到筛选的作用。 find方法 includes方法 some方法和ar ...

数组的方法

数组的的大部分方法都可以实现数组的遍历。

foreach方法

实现数组的遍历

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.foreach(function (value, index, arr) {
    cosnole.log(value, index, arr);
});
// value ==> 值
// index ==> 值对应的下标
// arr ==> 遍历的数组对象

map方法

map方法的作用:会生成一个与遍历对象数组相同长度的新数组,并且map中的返回值就是新数组的参数值。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const narr = arr.map(function (value) {
    return value;
})
// 此时narr中的值与arr中的值相等
// 当方法中的函数只有一个形参和函数内部只有return时,可以写成下面的方式
const narr = arr.map(value => value);
// 箭头函数

filter方法

过滤,起到筛选的作用。

// 例如:筛选出数组arr中的奇数
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const oddarr = arr.filter(num => num % 2);

find方法

// 查找
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = arr.find(value => value > 3);
// num的值为4,find方法会返回满足条件的第一个结果

includes方法

// 对比arr.indexof(value) 判断对应的值在数组中的下标,有则返回下标,否则返回-1
// arr.includes(value) 只要存在于数组则返回true,否则返回false
// 该方法不会遍历数组
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arr.includes(1)); //true
console.log(arr.includes(9)); //false

some方法和array方法

  • some是判断数组中是否存在满足条件的值,满足返回true,否则返回false。
  • array是判断数组中的值是否全部满足条件,满足返回true,否则返回false。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网