使用Underscore.js
Underscore.js 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。Underscore 提供了100多个函数,包括常用的:map、filter、invoke — 当然还有更多专业的辅助函数,如:函数绑定、JavaScript 模板功能、创建快速索引、强类型相等测试等等。 微信小程序无法直接使用require( 'underscore.js' )进行调用。
var _ = require('../../libs/underscore/underscore.modified');
//获取应用实例
var app = getApp();
Page({
onLoad: function() {
//console.log('onLoad');
var that = this;
var lines = [];
lines.push("_.map([1, 2, 3], function(num){ return num * 3; });");
lines.push(_.map([1, 2, 3], function(num) { return num * 3; }));
lines.push("var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);");
lines.push(_.reduce([1, 2, 3], function(memo, num) { return memo + num; }, 0));
lines.push("var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });");
lines.push(_.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }));
lines.push("_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });");
lines.push(_.sortBy([1, 2, 3, 4, 5, 6], function(num) { return Math.sin(num); }));
lines.push("_.indexOf([1, 2, 3], 2);");
lines.push(_.indexOf([1, 2, 3], 2));
this.setData({
text: lines.join('n')
})
}
})
|
使用Immutable.js
Immutable 是 Facebook 开发的不可变数据集合。不可变数据一旦创建就不能被修改,是的应用开发更简单,允许使用函数式编程技术,比如惰性评估。Immutable JS 提供一个惰性 Sequence,允许高效的队列方法链,类似 map 和 filter,不用创建中间代表。immutable 通过惰性队列和哈希映射提供 Sequence, Range, Repeat, Map, OrderedMap, Set 和一个稀疏 Vector。
var Immutable = require( '../../libs/immutable/immutable' );
//获取应用实例
var app = getApp();
Page( {
onLoad: function() {
console.log('onLoad');
var that = this;
var lines = [];
lines.push( "var map1 = Immutable.Map({a:1, b:2, c:3});" );
var map1 = Immutable.Map({a:1, b:2, c:3});
lines.push( "var map2 = map1.set('b', 50);" );
var map2 = map1.set('b', 50);
lines.push( "map1.get('b');" );
lines.push(map1.get('b'));
lines.push( "map2.get('b');" );
lines.push(map2.get('b'));
this.setData( {
text: lines.join( 'n' )
})
}
})
|
使用UUID、Base64、Chance
node-uuid模块,可以快速地生成符合 RFC4122 规范 version 1 或者 version 4 的 UUID。
js-base64 是 Base64 的 JavaScript 实现。
Chance 是一个基于 JavaScript 的随机数工具类。可以生成随机数字,名称,地址,域名,邮箱,时间等等,几乎网站中使用的任何形式的内容都能够生成。这个随机数工具可以帮助减少单调的测试数据编写工作,特别是编写自动化测试的时候。
var uuid = require('../../libs/node-uuid/uuid.modified');
var Base64 = require('../../libs/js-base64/base64.modified');
var Chance = require('../../libs/chance/chance');
//获取应用实例
var app = getApp();
Page({
onLoad: function() {
//console.log('onLoad');
var that = this;
// UUID
// v1 是基于时间戳生成uuid
console.log(uuid.v1());
// v4 是随机生成uuid
console.log(uuid.v4());
console.log('');
// Base64
console.log(Base64.encode('Wechat'));
console.log(Base64.encode('微信'));
console.log(Base64.decode('V2VjaGF0'));
console.log(Base64.decode('5b6u5L+h'));
console.log('');
// Chance
var chance = new Chance();
console.log(chance.string());
console.log(chance.integer());
console.log(chance.bool());
console.log(chance.phone());
console.log(chance.zip());
console.log(chance.guid());
}
})
|












