不知道爲什麼這不起作用。不應該返回索引並停止循環。 我只需要返回這是真的第一個值的索引,然後在數組中不返回其他任何下劃線每種方法不返回值
var index = _.each([false, true, true],function(flag, index){
if(flag){ return index }
});
不知道爲什麼這不起作用。不應該返回索引並停止循環。 我只需要返回這是真的第一個值的索引,然後在數組中不返回其他任何下劃線每種方法不返回值
var index = _.each([false, true, true],function(flag, index){
if(flag){ return index }
});
_.each
調用迭代函數的每一個元素,不管你什麼回報。我認爲_.indexOf
是你正在尋找。
var index = _.indexOf([false, true, true], true);
_.each
只是一個迭代器,不會返回索引。用它來找到你盡力做一個索引,你會想要做的事,如:
var trueIndex = -1;
_.each([false, true, true],function(flag, index){
if (trueIndex < 0 && flag) {
trueIndex = index;
}
});
if (trueIndex != -1) {
alert(trueIndex);
}
它可能更容易,只需使用一個while循環,雖然:
var flags = [false, true, true]
var f, index = 0;
while(f = flags[index++]) {
if (f) break;
}
alert (index);
的indexOf只返回一個值,這是你所需要的:) 但是...您可以使用地圖過濾器,如果你需要所有的人:d也許還有一個更簡單的解決方案...
_(_.map([false, true, true], function(obj, index){ if(obj)return index; })).filter(function(num, index){return num != undefined});
這將返回一個數組:[1 ,2]
@邁克爾指數的解決方案可能比兩者都好。除了下劃線之外還有一段時間,請參閱:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf – rjz 2012-02-29 23:33:51