数组常用方法以及区别

filter()和find()的用法区别
应用场景1:假定有一个对象数组A,获取数组中指定类型的对象放到B数组中。
var products = [
  {
    name: "cucumber",
    type: "vegetable"
  },
  {
    name: "apple",
    type: "fruit"
  },
  {
    name: "orange",
    type: "fruit"
  }
];
var filters = products.filter(function(item) {
  return item.type == "fruit";
});
console.log(filters);
//结果:[{name: "apple", type: "fruit"},{name: "orange", type: "fruit"}]
应用场景2:假定有一个对象数组A,过滤掉不满足一下条件的对象,条件:水果 ,价格小于10,数量大于0。
var products = [
  {
    name: "cucumber",
    type: "vegetable",
    quantity: 10,
    price: 5
  },
  {
    name: "apple",
    type: "fruit",
    quantity: 0,
    price: 5
  },
  {
    name: "orange",
    type: "fruit",
    quantity: 1,
    price: 2
  }
];
var filters = products.filter(function(item) {
  //使用&符号将条件链接起来
  return item.type === "fruit" && item.quantity > 0 && item.price < 10;
});
console.log(filters);
//结果:[{name: "orange", type: "fruit", quantity: 1, price: 2}]
应用场景3:假定有对象A和数组B,根据A中id值,过滤掉B中不符合的数据。
var post = { id: 1, title: "A" };
var comments = [
  { postId: 3, content: "CCC" },
  { postId: 2, content: "BBB" },
  { postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
  return comments.filter(function(item) {
    return item.postId == post.id;
  });
}
console.log(commentsPost(post, comments));
//结果:[{postId: 1, content: "AAA"}],返回的是数组

注意:filter和find区别:filter返回的是数组,find返回的是对象。


2.find()用法详解
应用场景1:假定有一个对象数组A,找到符合条件的对象
var users = [
  { name: "jack", age: 12 },
  { name: "alex", age: 15 },
  { name: "eva", age: 20 }
];
var user = users.find(function(item) {
  return (item.name = "eva");
});
console.log(user);
//结果:{ name: "eva", age: 20 }
注:find()找到第一个元素后就不会在遍历其后面的元素,所以如果数组中有两个相同的元素,他只会找到第一个,第二个将不会再遍历了。

应用场景2:假定有一个对象数组A,根据指定对象的条件找到数组中符合条件的对象。
var post = { id: 1, title: "AAA" };
var comments = [
  { postId: 3, content: "CCC" },
  { postId: 2, content: "BBB" },
  { postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
  return comments.find(function(item) {
    return item.postId == post.id;
  });
}
console.log(commentsPost(post, comments));
//结果:{postId: 1, content: "AAA"},返回的是对象
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容