JavaScript查找一个数组中符合某个条件的值,并将符合条件的值存入新的数组

1. 利用find函数和es6箭头函数,下面方法取到数组中满足条件的第一个元素;

var newArray  = {};//新对象
var array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; 
//查找符合条件值并存入新数组
newArrar = this.array.find((item) => {
   if(item.name === 'sisi'){
     return item
   }
 })
//此时 newArray = {name:'sisi',age:18}

2. 查找符合条件的所有元素

var newArray  = [];//新数组
var j = 0;
var array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; //目标数组
 
//查找符合条件值并存入新数组
for(let i in array){
 if(array[i].name == 'sisi'){
  newArray[j++] = array[i]
 }
}
//此时 newArray = [{name:'sisi',age:18},{name:'sisi',age:19}]

你可能感兴趣的:(javascript,linux,开发语言)