ES2015(es6)和Underscore的一些用法比较

来源:互联网 发布:水电费软件 编辑:程序博客网 时间:2024/05/24 08:34
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="underscore.js"></script></head><body><script>
//需要使用的童鞋可以下载一个underscore尝试一下   _.each([1, 2, 3], function (list, index) {        console.log(list + ":" + index);    });//Underscore遍历        [1, 2, 3].forEach( (value,index)=>console.log(value + ":" + index))  //ES5.1遍历var array =  _.map([1, 2, 3], function(num){ return num * 3; }) console.log(array)//Underscore映射新数组[1, 2, 3].map( (num)=> console.log(num*3))//ES5.1映射新数组var lists = _.filter([1, 2, 3, 4, 5, 6], function(num){    return num % 2 == 0;}) console.log(lists)//Underscore过滤var lists = [1, 2, 3, 4, 5, 6].filter((num) => num%2==0)  //ES2015过滤console.log(lists) //find只找到第一个符合条件的值var users = [    {name: 'moe', age: 40},    {name: 'larry', age: 50}];console.log( _.pluck(users, 'name'));//Underscore萃取数组对象中某属性值 var lists = [    {name: 'moe', age: 40},    {name: 'larry', age: 50}].map(value => value['name']);console.log(lists) //ES2015萃取数组对象中某属性值console.log(_.contains([1, 2, 3], 3));//Underscore判断元素是否在list中console.log([1, 2, 3].includes(3))//ES2016判断元素是否在list中console.log(        (function () {            return _.toArray(arguments).slice(1);        })(1, 2, 3, 4));//Underscore把一个类数组转换成一个数组console.log(        (function () {            return Array.from(arguments).slice(1);        })(1, 2, 3, 4));//ES2015把一个类数组转换成一个数组 console.log(_.compact([0, 1, false, 2, '', 3]))//Underscore返回一个除去所有false值的array副本,javascript中 false, null, 0, "", undefined 和 NaN 都是false值.console.log( [0, 1, false, 2, '', 3].filter(x => !!x))  //    ES2015返回一个除去所有false值的array副本console.log(_.uniq([1, 2, 1, 3, 1, 4])) //Underscore返回 array去重后的副本console.log([...new Set([1, 2, 1, 3, 1, 4])]) //ES2015返回 array去重后的副本console.log(_.range(0, 30, 5)) //Underscore创建整数灵活编号的列表的函数,便于each 和 map循环console.log(Array.from({ length: 5 }, (v, k) => k + 0)) //ES2015创建一个 N个数字数组,从x开始(不知道怎么给定范围,尴尬)console.log(_.keys({one: 1, two: 2, three: 3})) //Underscore枚举自身的属性名console.log(Object.keys({one: 1, two: 2, three: 3})) //ES2015枚举自身的属性名function Stooge(name) {    this.name = name;}Stooge.prototype.silly = true;console.log(_.allKeys(new Stooge("Moe"))) //Underscore检索object拥有的和继承的所有属性的名称console.log(  Reflect.enumerate(new Stooge("Moe"))) // ES2015返回一个迭代器(Reflect.enumerate is not a function)*/var moe = _.create(Stooge.prototype, {name: "Moe"});console.log(moe)  //Underscore创建具有给定原型的新对象, 可选附加props 作为 own的属性,和Object.create一样, 但是没有所有的属性描述符console.log(_.extend({b:2}, {c:3}, { a: false }))//Underscore复制并扩展对象console.log({ ...Stooge, a: false }) //es2016暂不讨论console.log(_.isFinite(2017.2)) //Underscore判断对象是否是一个有限的数字;ES2015 Number.isFinite//(给对象绑定一个函数)//Underscorefoo(function () {    this.bar();}.bind(this));foo(_.bind(object.fun, object));//ES2015foo(() => {    this.bar();});foo(object.fun.bind(object));//ES2016foo(() => {    this.bar();});foo(::object.fun);</script></body></html>
1 0
原创粉丝点击