ES6数组操作:forEach、map、filter、find、every、some、reduce、concat(合并)详细用法

目录

ES6数组操作:forEach、map、filter、find、every、some、reduce详细用法

1、forEach

2、map

3、filter

4、find

5、every

6、some

7、reduce

8、concat(合并)



ES6数组操作:forEach、map、filter、find、every、some、reduce、concat(合并)详细用法

1、forEach

作用:循环遍历

numbers=[1,2,3,4,5]
numbers.forEach(number => {
    console.log(number)  //1 2 3 4 5
});

2、map

作用:遍历,类似于forEach

3、filter

作用:过滤筛选数组,返回过滤后的新数组

var products = [
    {name:"cucumber",type:"vegetable"},
    {name:"banana",type:"fruit"},
    {name:"celery",type:"vegetable"},
    {name:"orange",type:"fruit"}
  ]; 
  var filtered = products.filter((product)=>{
    return product.type === "vegetable";
  })
  console.log(filtered)  
//[{name:"cucumber",type:"vegetable"},{name:"celery",type:"vegetable"}]

4、find

作用:在数组中找到符合要求的对象 和filter的区别就是找到符合要求的第一个对象就停止寻找了,返回的是一个对象,而filter返回的是所有符合要求的对象组成的新数组

var post = {id:4,title:"Javascript"};
 var comments = [
    {postId:4,content:"Angular4"},
    {postId:2,content:"Vue.js"},
    {postId:3,content:"Node.js"},
    {postId:4,content:"React.js"}   
 ];
 function commentsForPost(post,comments){
    var v=comments.find(function(comment){
      return comment.postId === post.id;
    })   //返回查找到的某一项
    return v.content;    //返回找到的某项的某个值
 }
 
 console.log(commentsForPost(post,comments));  // {postId:4,content:"Angular4"}

5、every

作用:若目标数组中每一个对象都符合设置的条件,则返回true,否则返回false

var users = [
    {name:"Jill",age:10},
    {name:"Alex",age:18},
    {name:"Bill",age:20},
    {name:"Tony",age:24}
   ];
 
   var isAdult_every=users.every(user=>{
      return user.age>18;
   })
 
   console.log(isAdult_every)  //false

6、some

作用:若目标数组中至少有一个符合设置的条件,则返回true,否则返回false

var users = [
    {name:"Jill",age:10},
    {name:"Alex",age:18},
    {name:"Bill",age:20},
    {name:"Tony",age:24}
   ];
 
   var isAdult_some=users.some(user=>{
    return user.age>18;
 })
 
 
   console.log(isAdult_some)  //true

7、reduce

作用:常用语叠加,可以代替forEach

8、concat(合并)

作用:合并、复制数组;不传参数就是复制,传参数就是合并

var arr1=['a','b','c','d'];
var arr2=['d'];
var arr3=['e','f'];
var cc=arr1.concat(arr2,arr3);
console.log(cc);//["a", "b", "c", "d", "d", "e", "f"]

 

你可能感兴趣的:(ES6,JavaScript)