1.Lodash 的随机数生成函数
//原生js
function getsRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
getsRandomNumber(20, 100);
console.log(getsRandomNumber(20, 100));
// Lodash
console.log(_.random(20, 30));
console.log(_.random(15, 20,true))
2.对象扩展
//原生js
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
var objAa = {
"name": "小明明",
"car": "丰田"
};
var objBb = {
"name": "小咪咪",
"age": 200,
"marks": 100
};
objAa.extend(objBb);
console.log(objAa) // {"name": "james", "age": 17, "car": "suzuki"};
// Lodash
_.assign(objAa, objBb)
console.log(_.assign(objAa, objBb))
_.assign 是浅拷贝, 和ES6新增的 Object.assign 函数功能一致(建议优先使用Object.assign)。
3.筛选属性
var objAba = {
"name": "小敏敏",
"car": "大众",
"age": 100
};
//objAba.remove(['car', 'age']);
//console.log(objAba); // {"name": "colin"}
// Lodash
//objAba = _.omit(objAba, ['car', 'age']);
//console.log(objAba)
// => {"name": "小敏敏"}
//objAba = _.omit(objAba, "car");
//console.log(objAba)
// => {"name": "小敏敏", "age": 100}
objAba = _.omit(objAba, _.isNumber);
console.log(objAba)
4._.pick 是 _.omit 的相反操作,用于从其他对象中挑选属性生成新的对象。
var objuserinfo = {
"name": "夏米",
"car": "大众",
"age": 200
};
//var objB = objA.pick(['car', 'age']);
//console.log(objB)
// => {"car": "suzuki", "age": 17}
// Lodash
var objB = _.pick(objuserinfo, ['name', 'age']);
// => {"car": "suzuki", "age":17}
console.log(objB)
5.随机元素
var luckNum = ["AA", "BB", "CCC", "HHH", "GGG"];
function pickRandom(luckNum) {
var index = Math.floor(Math.random() * (luckNum.length - 1));
return luckNum[index];
}
pickRandom(luckNum); //John
console.log(pickRandom(luckNum))
// Lodash
_.sample(luckNum); //
console.log(_.sample(luckNum)); //
// Lodash - Getting 2 random item
//_.sample(luckNum, 2); //
6.针对 JSON.parse 的错误处理
// Using try-catch to handle the JSON.parse error function parse(str){ try { return JSON.parse(str); } catch(e) { return false; } } // With Lodash function parseLodash(str){ return _.attempt(JSON.parse.bind(null, str)); } parse('a'); // => false parseLodash('a'); // => Return an error object parse('{"name": "小咪咪"}'); // => Return {"name": "小咪咪"} parseLodash('{"name": "小咪咪"}'); // => Return {"name": "小咪咪"}