Lodash - findIndex 方法



語法

_.findIndex(array, [predicate=_.identity], [fromIndex=0])

此方法與 _.find 類似,但返回第一個元素謂詞的索引,而不是元素本身。

引數

  • array (陣列) − 需要檢查的陣列。

  • [predicate=_.identity] (函式) − 每次迭代呼叫的函式。

  • [fromIndex=0] (數字) − 開始搜尋的索引。

輸出

  • (數字) − 返回找到的元素的索引,否則返回 -1。

範例

var _ = require('lodash');
var users = [
   { user: 'Sam', active: false },
   { user: 'Ted', active: true },
   { user: 'Julie', active: false }
];

var result = _.findIndex(users, function(user) { return !user.active; });
console.log(result);

result = _.findIndex(users, ['active', false]);
console.log(result);

將以上程式儲存在 tester.js 中。執行以下命令以執行此程式。

命令

\>node tester.js

輸出

0
0
lodash_array.htm
廣告
© . All rights reserved.