2.8 findWhere
2.8.1 語法:
_.findWhere(list, predicate)
2.8.2 說明:
對list集合的每個對象依次與predicate對象進行匹配,匹配成功則立即返回此對象
- list可以為數組和arguments
- predicate是一個對象
2.8.3 代碼示例:
示例一:findWhere對數組,arguments進行操作,與predicate對象進行匹配(數組內需為對象)
var result;
result = _.findWhere([{x: 1, y: 2},{x: 1, z: 3}], {x: 1});
console.log(result) //=> {x: 1, y: 2}
//操作arguments
function abc() {
result = _.findWhere(arguments, {z: 3});
console.log(result); //=> {x: 1, z: 3}
}
abc({x: 1, y: 2}, {x: 1, z: 3});
示例二:predicate需要是一個對象否則直接返回list集合的第一個對象
var result;
result = _.findWhere([{x: 1, y: 2},{x: 1, z: 3}], {x: 1});
console.log(result) //=> {x: 1, y: 2}
// 非對象的情況
result = _.findWhere([{x: 1, y: 2},{z: 3}], null);
console.log(result) //=> {x: 1, y: 2}
2.8.4 list非數組且predicate沒值得的時候會怎樣?
// list為字符的情況
var result = _.findWhere('123');
console.log(result) //=> "1" list為字符串會返回字符串的第一個字符
// list為對象的情況
var result = _.findWhere({x: 1, y: '2'});
console.log(result) //=> 1 list為對象會返回對象的第一個屬性值
2.8.5 基本用法已經知道怎么用了,是否有遺漏呢?
示例一:我們現在已經知道predicate為空的情況下回返回第一個屬性值,如果匹配不到則會返回什么呢?
var result;
result = _.findWhere([{x: 1, y: 2},{x: 1, z: 3}], {x: 10});
console.log(result) //=> undefined
gitbook地址:https://www.gitbook.com/book/niec-fe/underscorejs/details