Underscore.JS - find 方法



语法

_.find(list, predicate, [context])

find 方法在给定的元素列表中进行迭代,对每个元素调用谓词。它返回第一个匹配的用例。如果没有找到匹配,则返回 undefined。此函数在找到匹配的元素时返回,而不进一步深入列表。

示例

var _ = require('underscore');

var list = [1, 2, 3, 4, 5, 6]
//Example 1. find first even number
var result = _.find(list, function(num) { return num % 2 == 0 });
console.log(result);

//Example 2. find first odd number
var result = _.find(list, function(num) { return !(num % 2 == 0) });
console.log(result);

将上述程序保存在 tester.js 中。运行以下命令以执行此程序。

命令

\>node tester.js

输出

2
1
underscorejs_iterating_collection.htm
广告
© . All rights reserved.