码迷,mamicode.com
首页 > 其他好文 > 详细

underscore arrays

时间:2015-08-17 21:45:13      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

_.first = _.head = _.take = function(array, n, guard) {
  //n == null--array[0];
  //n != null;guard == ture;--array[0]
  //n != null;guard == false;--返回前n个元素
return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; };
_.initial = function(array, n, guard) {
  //n == null--1;
  //n != null;guard == true--1
  //n != null;guard != true--n return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); };
//倒序指定的n个元素
slice.call(array, Math.max(array.length-n, 0));

_.rest跟_.initail很像

_.compact:返回能被转为true的元素 filter返回满足验证的元素

_.flatten:多维数组转为一维数组 reduce对元素进行迭代,迭代器返回memo

_.without与_.difference类似;前者的第二参数为元素,后者的第二参数为数组

_.intersection()获取多个数组的交集元素;

_.indexOf = function(array, item, isSorted) {
	if (array == null) return -1;
	var i, l;
	if (isSorted) {
	  i = _.sortedIndex(array, item);
      //写的真好,以后不用if了 return array[i] === item ? i : -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; return -1; };

_.range():创建数组,内容为连续数字

//如果start=undefined,则stop为0;如果start不为undefined,则stop=start
stop = start || 0;
start = 0;

_.zip():

_.zip([‘moe‘, ‘larry‘, ‘curly‘], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

 

underscore arrays

标签:

原文地址:http://www.cnblogs.com/wang-jing/p/4737605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!