underscore应用

        判断一个对象数组是否包含某个对象,可以用underscore的方法判断,代码简洁易懂。如contains、indexOf、find、findWhere,需要说明的是contains和indexOf使用===检测。简单实例如下:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="@my_coder">
<meta name="viewport"
	content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>underscore</title>
</head>

<body>
	<script type="text/javascript" src="underscore.js"></script>
	<script>
		var testList = [];
		testList.push({name:'zhangshan',age:18});
		testList.push({name:'lisi',age:28});
		testList.push({name:'wangwu',age:38});
		testList.push({name:'xiaomazi',age:88});
		//var res1 = _.contains(testList, {name:'zhangshan',age:18});
		var res1 = _.indexOf(testList, {name:'zhangshan',age:18});
		console.log("res1:" + res1);  //res1:-1
		
		var t = {name:'zhangshan0',age:16};
		var res4 = _.findWhere(testList, t);
		console.log("res4:" + res4); //res4:undefined
		if(!res4) {
			testList.push(t);
		}
		console.log(testList);
		
		var testList2 = [];
		var obj1 = {name:'zhangshan',age:18};
		var obj2 = {name:'lisi',age:28};
		var obj3 = {name:'wangwu',age:38};
		var obj4 = {name:'xiaomazi',age:88};
		testList2.push(obj1);
		testList2.push(obj2);
		testList2.push(obj3);
		testList2.push(obj4);
		//var res2 = _.contains(testList2, obj1);
		var res2 = _.indexOf(testList2, obj1);
		console.log("res2:" + res2);  //res2:0
		
		var res3 = _.find(testList, function(obj){ return obj.name == 'zhangshan'; });
		console.log("res3:" + res3);  //res3:[object Object]
	</script>
</body>
</html>

Underscore.js中文文档地址:http://www.css88.com/doc/underscore/

相关推荐