underscore js 笔记
underscore 是轻量级的js工具包。压缩后 4.9k,内置了 80 个有用的函数。不绑定 DOM,只是相当于高级的 js 语法。
- jquery 关注 DOM 操作
- backbone.js 组织js代码MVC结构
- underscore 一些小工具。templating 不错
Collections
each
_.each([1, 2, 3],function(d){console.log(d)});
Utility
times 执行多次
_(3).times(alert)
escape js 自带 escape 是 html url 转义;_.escape 是 html 转义
console.log(_.escape('><&')); console.log(escape('=""><&')); <="" pre="">uniqueId 生成全局唯一id
_.uniqueId('contact_');template
- <% … %> 执行js
- <%= … %> 输出变量
- <%- … %> 输出变量转义
例子 在 <template> 定义 html 模版,js中,获得该模版(并反转义),然后 ajax guoshuang.json,data 打进入,将返回的 html 渲染。
<%= name%> skills
- <%= Object.keys(k) %> : <%= k[Object.keys(k)] %>
<% _.each(favorites,function(k,key,list){ %>
<% }) %>
也可以 <% print(‘name:’+name) %> 等价于 name:<%=name%>
改为 mustache 语法
_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g }; var template = _.template("Hello !"); template({name: "Mustache"}); => "Hello Mustache!"
_.template 完整写法:
_.template(模版,数据,指定数据)
_.template("Using 'with': <%= data.answer="" %="">", {answer: 'no'}, {variable: 'data'}) %=>
clone 克隆对象(数组)
a=[1,2,3]; b=a; c=_.clone(a); b[0]=999; console.log('a 是'+a); console.log('c 是'+c);
size
_.size({one: 1, two: 2, three: 3}); => 3
compact 数组压缩
_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3]
union 合并多个数组
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2, 3, 101, 10]
intersection 多个数组交集(都有的部分)
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2]
difference 不在后面那些数组(们)中
_.difference([1, 2, 3, 4, 5], [5, 2, 10]); => [1, 3, 4]
object 数组转object
_.object(['moe', 'larry', 'curly'], [30, 40, 50]); => {moe: 30, larry: 40, curly: 50}
indexOf
_.indexOf(array, value, [isSorted]) 在 array 中找到 value,返回序号
If you’re working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search … or, pass a number as the third argument in order to look for the first matching value in the array after the given index.
_.indexOf([1, 2, 3], 2); => 1
uniq 数组去掉重复(注意:对比时使用的是 === 绝对相等)
a=[1,2,3,4,3,4,5,7] [1, 2, 3, 4, 3, 4, 5, 7] b=_.uniq(a) [1, 2, 3, 4, 5, 7]
range 返回从 20 到 60 每隔3 的数组
_.range(20,60,3) [20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59]
max
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]; _.max(stooges, function(stooge){ return stooge.age; }); => {name: 'curly', age: 60};
shuffle 打乱
_.shuffle([1, 2, 3, 4, 5, 6]); => [4, 1, 6, 3, 5, 2]
countBy
_.countBy([1, 2, 3, 4, 5], function(num) { return num % 2 == 0 ? 'even': 'odd'; }); => {odd: 3, even: 2}
find
_.find(list, iterator, [context]) 返回 list 中第一个符合 iterator 的对象,然后停止遍历
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); => 2
filter 过滤
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); => [2, 4, 6]&'));>&'));>