如何在阵列特定项目基本比较循环lodash内 [英] How to compare specific items in array inside of basic lodash loop
问题描述
这是循环的基本的JavaScript,我试图取代:
This is the basic JavaScript for loop I'm trying to replace:
for (var i=0; i<tickers.length; i++) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
break;
}
}
下面是 lodash 版
_.times((tickers.length), function() {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
这显然目前出现了错误,因为没有 [I]
在lodash版本变量集。
Obviously this errors out currently, because there is no [i]
variable set in the lodash version.
该lodash版本更可读恕我直言,只是做了很多次我的行情数组的长度。
The lodash version is much more readable imho, just do this many times the length of my tickers array.
不过,我需要比较每个对象的股票的 selectedTicker
。
However I need to compare the ticker of each object to the selectedTicker
.
更新:添加屏幕截图和链接来证明一些问这个_lodash比原生的JavaScript速度
http://jsperf.com/forloop-vs-each-from-lodash
推荐答案
您需要通过 I
成在lodash函数的回调。这应该工作:
You need to pass i
into the callback in the lodash function. This should work:
_.times((tickers.length), function(i) {
if (tickers[i].ticker === selectedTicker) {
selectTicker('portfolio', tickers[i]);
return;
}
});
另外,如果你能够使用ES6语法,就可以实现通过使用相同的结果过滤
var ticker = tickers.filter(t => t.ticker === selectedTicker)[0];
if(ticker){
selectTicker('portfolio', ticker);
}
这篇关于如何在阵列特定项目基本比较循环lodash内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!