underscorejs :_.findWhere(list, predicate):
说明:
对list集合的每个对象依次与predicate对象进行匹配,匹配成功则立即返回此对象
- list可以为数组和arguments
- predicate是一个对象
示例一: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}
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为对象会返回对象的第一个属性值
基本用法已经知道怎么用了,是否有遗漏呢?
var result; result = _.findWhere([{x: 1, y: 2},{x: 1, z: 3}], {x: 10}); console.log(result) //=> undefined