[英]How to find element in array
I'm really new to javascript and I have an array of objects. 我是javascript的新手,我有一个对象数组。
var cart = [
{ id: 1, price: 2 },
{ id: 2, price: 1 }
];
and I'm using a for loop to find the ID: 我正在使用for循环来查找ID:
for (var i = 0; i < cart.length; i++) {
if (cart[i].id === id) {
return cart[i]
}
}
return null;
I know there's functions like find()
, but I'm not too sure on how to use that. 我知道有像
find()
这样的函数,但是我不太清楚如何使用它。 Can anyone help? 有人可以帮忙吗?
With find , you might need babel , but just the code you need: 使用find ,您可能需要babel ,但只需要您需要的代码:
ES6
const id = 1;
const found = cart.find(item => item.id === id)
Vanilla
var id = 1;
var found = cart.find(function(item) {return item.id === id})
find
takes a function (in our case with es6: () => {}
is an anonymous function), and applies it to every item in the list, until it finds the first match, how does it know when it is a match: once your function returns true, then it cuts the loop, and returns the item. find
需要一个函数(在我们的例子中使用es6 : () => {}
是一个匿名函数),并将它应用于列表中的每个项目,直到找到第一个匹配项,它是如何知道它是匹配的:一旦你的函数返回true,它就会切断循环,并返回该项。
HOWEVER 然而
Another option, that does not use find but might be more readable than a traditional for loop: 另一个选项,它不使用find但可能比传统的for循环更具可读性:
var id = 1;
for(var item in cart) {
if(item.id == id) {
return item;
}
}
return null
There are also a slew of libraries out there that can help you achieve this on different ways, ex: underscore.js , lodash , which I will not cover, but you can take a look at if you are really interested. 还有一些库可以帮助你以不同的方式实现这一点,例如: underscore.js , lodash ,我不会介绍,但你可以看看你是否真的感兴趣。
You are right. 你是对的。 There is a function called find .
有一个名为find的函数。 You can set up the callback function to use with
find
, and even set it up to accept a parameter (such as the id
): 您可以设置回调函数以与
find
一起使用,甚至可以将其设置为接受参数(例如id
):
var cart = [{ id: 1, price: 2 }, { id: 2, price: 1 }]; function byID(id) { return function(element) { return element.id == id; } } var item = cart.find(byID(2)); console.log(item);
With issues like this, I very much appreciate the library lodash . 对于这样的问题,我非常感谢图书馆lodash 。 It allows you to do things like so:
它允许你做这样的事情:
var cart = [{id: 1, price: 5}, {id: 2, price: 6}]; var item = _.find(cart, {id:2}); console.log(item);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.