_.find()函數查看列表中的每個元素,並返回滿足條件的元素的第一個匹配項。如果列表的任何元素不滿足條件,則返回undefined
值。
用法:
_.find(list, predicate, [context])
參數:該函數接受上述和以下所述的三個參數:
- list:此參數用於保存項目列表。
- predicate:此參數用於保存真值條件。
- context:需要顯示的文本內容。它是一個可選參數。
返回值:它返回滿足條件的元素的第一次出現。
範例1:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var oddNo = _.find([5, 6, 7, 8, 9, 10],
function (num) {
return num % 2 != 0;
});
console.log(oddNo);
</script>
</body>
</html>
輸出:
5
範例2:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var words = ['javascript', 'java', 'unix',
'hypertext', 'undescore', 'CSS'];
const result = words.find(word => word.length == 9);
console.log(result);
</script>
</body>
</html>
輸出:
hypertext
相關用法
- Javascript Array find()用法及代碼示例
- PHP Ds\Deque find()用法及代碼示例
- PHP Ds\Sequence find()用法及代碼示例
- PHP Ds\Vector find()用法及代碼示例
- Mongoose find()用法及代碼示例
- Javascript Array.find()用法及代碼示例
- Javascript typedArray.find()用法及代碼示例
注:本文由純淨天空篩選整理自AshokJaiswal大神的英文原創作品 Underscore.js | _.find() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。