您的位置:首页 > Web前端 > JavaScript

underscorejs-findWhere学习

2016-01-27 10:31 531 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: