<script>
//filter方法
/**场景1
*
*假定有一个对象数组(A),获取数组中指定类型的对象放到B数组中
*/
// ES5
var products = [
{name:'cucumber',type:'vegetable'},
{name:'banana',type:'fruit'},
{name:'celery',type:'vegetable'},
{name:'orange',type:'fruit'}
]
var fillterarry =[];
for(var i=0;i<products.length;i++){
if(products[i].type==='fruit'){
fillterarry.push(products[i].name)
}
}
document.write(fillterarry)
// ES6
var filterList= products.filter((product)=>{
return product.type === ‘fruit’
})
console.log(filterList)
/**场景2
*
*假定有一个对象数组(A),过滤掉不满足以下条件的对象
*条件:蔬菜 数量大于0,价格小于10
*/
var products = [
{name:‘cucumber’,type:‘vegetable’,sum:10,price:10},
{name:‘banana’,type:‘fruit’,sum:0,price:0},
{name:‘celery’,type:‘vegetable’,sum:11,price:5},
{name:‘orange’,type:‘fruit’,sum:70,price:10}
]
var newArry = products.filter((product)=>{
return product.type === ‘vegetable’ && product.sum>0 && product.price<10
})
console.log(newArry)
/**场景3
*
*假定有两个数组(A,B),根据A中id值,过滤掉B数组不符合的数据
*/
var post ={id:4,title:‘javascript’};
var comments =[
{id:4,title:‘javascript’},
{id:2,title:‘Vue.js’},
{id:3,title:‘Node.js’},
{id:1,title:‘React.js’}
]
function commentsVal(post,comments){
return comments.filter((comment)=>{
return comment.id === post.id
})
}
console.log(commentsVal(post,comments))
//find方法
/**场景1
*
*假定有一个对象数组(A),找到符合条件的对象
*/
var user = [
{name:‘jill’},
{name:‘mill’},
{name:‘xiaotan’},
{name:‘xing’}
]
//ES5
var username;
for(var i=0;i<user.length;i++){
if(user[i].name=='mill'){
username = user[i];
break;
}
}
console.log(username)
//es6
username = user.find((item)=>{
return item.name == 'xiaotan'
})
console.log(username)
/**场景2
*
*假定有一个对象数组(A),根据指定对象的条件找到数组中符合条件的对象
*/
var post1 ={id:4,title:'Node.js'};
var posts = [
{id:1,title:'Node.js'},
{id:4,title:'Vue.js'}
]
function comments1(post1,posts){
return posts.find((comment)=>{
return comment.id === post1.id
})
}
console.log(comments1(post1,posts))