简体   繁体   English

JavaScript中的最佳循环允许返回值?

[英]Best loop in javascript that allows returning of value?

There are a few loops in javascript including forEach, some, map, and reduce. javascript中有几个循环,包括forEach,一些循环,映射和reduce。 However, from what I currently understand, none of these are appropriate if you want to iterate through an array and return the value of a particular index. 但是,从我目前的理解来看,如果您想遍历数组并返回特定索引的值,那么这些都不适合。 It seems like I am pretty much left with the standard for loop only. 似乎我只剩下标准的for循环了。 Is that true? 真的吗?

So for instance, if I have an array of objects... and I would like to find the index of the item with a particular value... could I use anything other than the regular for loop? 因此,例如,如果我有一个对象数组……并且我想找到具有特定值的项目的索引……除了常规的for循环之外,我还可以使用其他任何东西吗?

There is also the for ... of ... : 还有for ... of ...for ... of ...

for (variable of iterable) {
  statement
}

You can use a JavaScript library http://underscorejs.org . 您可以使用JavaScript库http://underscorejs.org It have plenty of functions. 它具有很多功能。 for your purpose you can use _.indexOf . 为了您的目的,您可以使用_.indexOf it will eturns the index at which value can be found in the array 它将返回可以在数组中找到值的索引

example: 例:

var data=[1, 2, 3];
var index= _.indexOf(data, 2);

out put will be 1 输出将是1

Array.prototype.findIndex() , as suggested by @Andreas in comments. Array.prototype.findIndex() ,由@Andreas在注释中建议。

You can pass in a function to findIndex() method and define your equality criteria in that function. 您可以将一个函数传递给findIndex()方法,并在该函数中定义相等条件。

It will return the index of first array element, that satisfies the equality criteria defined in your function. 它将返回满足您的函数中定义的相等条件的第一个数组元素的索引。

You could use foreach() rather than regular for.It is the simplest and you can iterate and get the index. 您可以使用foreach()而不是常规的for。这是最简单的方法,您可以迭代并获取索引。 For more info: JavaScript Array forEach() Method 有关更多信息: JavaScript Array forEach()方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM