【5天打卡】学习Lodash的第三天——不需要使用的api

news/2024/7/10 23:16:23 标签: 学习, es6, javascript

大家好,最近,我在学习Lodash这个工具库。Lodash最初是 Underscore 的分支,后来逐渐壮大后自立门户。Lodash 功能比 Underscore 更丰富,且 Underscore 已有3、4年没有更新,所以推荐使用 Loadash。但是和原生相比还是推荐使用ES6等。

所以我们一起来学习Lodash,今天打卡第三天,加油!

目前, Lodash是最受依赖的npm软件包 ,但是如果您使用的是ES6,则可能实际上并不需要它。

建议以下方法用原生的方法:

  1. _.each
  2. _.map
  3. _.every
  4. _.some
  5. _.reduce
  6. _.reduceRight
  7. _.filter
  8. _.find
  9. _.findIndex
  10. _.indexOf
  11. _.lastIndexOf
  12. _.includes
  13. _.keys
  14. _.size
  15. _.isNaN
  16. _.reverse
  17. _.join
  18. _.toUpper
  19. _.toLower
  20. _.trim
  21. _.repeat
  22. _.after

_.each 遍历一系列的元素,并且调用回调处理方程

javascript">// Underscore/Lodash
_.each([1, 2, 3], function(value, index) {
  console.log(value);
});
// output: 1 2 3

// Native
[1, 2, 3].forEach(function(value, index) {
  console.log(value);
});
// output: 1 2 3

_.map 将某个列表中的元素映射到新的列表中

javascript">// Underscore/Lodash
var array1 = [1, 2, 3];
var array2 = _.map(array1, function(value, index) {
  return value*2;
});
console.log(array2);
// output: [2, 4, 6]

// Native
var array1 = [1, 2, 3];
var array2 = array1.map(function(value, index) {
  return value*2;
});
console.log(array2);
// output: [2, 4, 6]

_.every 测试数组的所有元素是否都通过了指定函数的测试

javascript">// Underscore/Lodash
function isLargerThanTen(element, index, array) {
  return element >=10;
}
var array = [10, 20, 30];
var result = _.every(array, isLargerThanTen);
console.log(result);
// output: true

// Native
function isLargerThanTen(element, index, array) {
  return element >=10;
}

var array = [10, 20, 30];
var result = array.every(isLargerThanTen);
console.log(result);
// output: true

_.some 判断序列中是否存在元素满足给定方程的条件

javascript">// Underscore/Lodash
function isLargerThanTen(element, index, array) {
  return element >=10;
}
var array = [10, 9, 8];
var result = _.some(array, isLargerThanTen);
console.log(result);
// output: true

// Native
function isLargerThanTen(element, index, array) {
  return element >=10;
}

var array = [10, 9, 8];
var result = array.some(isLargerThanTen);
console.log(result);
// output: true

_.reduce 接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值

javascript">// Underscore/Lodash
var array = [0, 1, 2, 3, 4];
var result = _.reduce(array, function (previousValue, currentValue, currentIndex, array) {
  return previousValue + currentValue;
});
console.log(result);
// output: 10

// Native
var array = [0, 1, 2, 3, 4];
var result = array.reduce(function (previousValue, currentValue, currentIndex, array) {
  return previousValue + currentValue;
});
console.log(result);
// output: 10

_.reduceRight 接受一个函数作为累加器(accumulator),让每个值(从右到左,亦即从尾到头)缩减为一个值。(与 reduce() 的执行方向相反)

javascript">// Underscore/Lodash
var array = [0, 1, 2, 3, 4];
var result = _.reduceRight(array, function (previousValue, currentValue, currentIndex, array) {
  return previousValue - currentValue;
});
console.log(result);
// output: -2

// Native
var array = [0, 1, 2, 3, 4];
var result = array.reduceRight(function (previousValue, currentValue, currentIndex, array) {
  return previousValue - currentValue;
});
console.log(result);
// output: -2

_.filter 使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组

javascript">// Underscore/Lodash
function isBigEnough(value) {
  return value >= 10;
} 
var array = [12, 5, 8, 130, 44];
var filtered = _.filter(array, isBigEnough);
console.log(filtered);
// output: [12, 130, 44]

// Native
function isBigEnough(value) {
  return value >= 10;
} 
var array = [12, 5, 8, 130, 44];
var filtered = array.filter(isBigEnough);
console.log(filtered);
// output: [12, 130, 44]

_.find 返回数组中满足测试条件的一个元素,如果没有满足条件的元素,则返回 undefined

javascript">// Underscore/Lodash
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// output: object for 'barney'

// Native
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

users.find(function(o) { return o.age < 40; });
// output: object for 'barney'

_.findIndex 用来查找数组中某指定元素的索引, 如果找不到指定的元素, 则返回 -1

javascript">// Underscore/Lodash
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var index =  _.findIndex(users, function(o) { return o.age >= 40; });
console.log(index);
// output: 1

// Native
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var index =  users.findIndex(function(o) { return o.age >= 40; });
console.log(index);
// output: 1

_.indexOf 返回指定值在字符串对象中首次出现的位置。从 fromIndex 位置开始查找,如果不存在,则返回 -1

javascript">// Underscore/Lodash
var array = [2, 9, 9];
var result = _.indexOf(array, 2);    
console.log(result); 
// output: 0

// Native
var array = [2, 9, 9];
var result = array.indexOf(2);    
console.log(result); 
// output: 0

_.lastIndexOf 返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始

javascript">// Underscore/Lodash
var array = [2, 9, 9, 4, 3, 6];
var result = _.lastIndexOf(array, 9);    
console.log(result); 
// output: 2

// Native
var array = [2, 9, 9, 4, 3, 6];
var result = array.lastIndexOf(9);    
console.log(result); 
// output: 2

_.includes 判断元素是否在列表中

javascript">var array = [1, 2, 3];
// Underscore/Lodash - also called with _.contains
_.includes(array, 1);
// → true

// Native
var array = [1, 2, 3];
array.includes(1);
// → true

_.keys 返回某个对象所有可枚举的键名

javascript">// Underscore/Lodash 
var result = _.keys({one: 1, two: 2, three: 3});
console.log(result);
// output: ["one", "two", "three"]

// Native
var result2 = Object.keys({one: 1, two: 2, three: 3});
console.log(result2); 
// output: ["one", "two", "three"]

_.size 返回集合大小

javascript">// Underscore/Lodash
var result = _.size({one: 1, two: 2, three: 3});
console.log(result);
// output: 3

// Native
var result2 = Object.keys({one: 1, two: 2, three: 3}).length;
console.log(result2); 
// output: 3

_.isNaN 判断是否为NaN

javascript">// Underscore/Lodash
console.log(_.isNaN(NaN));
// output: true

// Native
console.log(isNaN(NaN));
// output: true

// ES6
console.log(Number.isNaN(NaN));
// output: true

_.reverse 将一个序列反向

javascript">// Lodash
var array = [1, 2, 3];
console.log(_.reverse(array));
// output: [3, 2, 1]

// Native
var array = [1, 2, 3];
console.log(array.reverse());
// output: [3, 2, 1]

_.join 将一个序列变成一个字符串

javascript">// Lodash
var result = _.join(['one', 'two', 'three'], '--');
console.log(result);
// output: 'one--two--three'

// Native
var result = ['one', 'two', 'three'].join('--');
console.log(result)
// output: 'one--two--three'

_.toUpper 将字符串大写

javascript">// Lodash
var result = _.toUpper('foobar');
console.log(result);
// output: 'FOOBAR'

// Native
var result = 'foobar'.toUpperCase();
console.log(result);
// output: 'FOOBAR'

_.toLower 将字符串变为小写

javascript">// Lodash
var result = _.toLower('FOOBAR');
console.log(result);
// output: 'foobar'

// Native
var result = 'FOOBAR'.toLowerCase();
console.log(result);
// output: 'foobar'

_.trim 消去字符串起始的空白

javascript">// Lodash
var result = _.trim(' abc ');
console.log(result);
// output: 'abc'

// Native
var result = ' abc '.trim();
console.log(result);
// output: 'abc'

_.repeat 重复创建字符串

javascript">// Lodash
var result = _.repeat('abc', 2);
// output: 'abcabc'

// Native
var result = 'abc'.repeat(2);
console.log(result);
// output: 'abcabc'

_.after 创建一个在经过了指定计数器之后才会被调用的方程

javascript">var notes = ['profile', 'settings'];
// Underscore/Lodash
var renderNotes = _.after(notes.length, render);
   notes.forEach(function(note) {
   console.log(note);
   renderNotes();
});

 // Native
notes.forEach(function(note, index) {
 console.log(note);
 if (notes.length === (index + 1)) {
   render();
 }
});

拓展:用 es6 原生替代 lodash

javascript">_.forEach([1, 2, 3], (i) => { console.log(i) })
_.map([1, 2, 3], (i) => i + 1)
_.filter([1, 2, 3], (i) => i > 1)
_.reduce([1, 2, 3], (sum, i) => sum + i, 0)

// 使用 ES6 改写
[1, 2, 3].forEach((i) => { console.log(i) })
[1, 2, 3].map((i) => i + 1)
[1, 2, 3].filter((i) => i > 1)
[1, 2, 3].reduce((sum, i) => sum + i, 0)
javascript">// 头尾元素
_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]

// 使用ES6改写
const [head, ...tail] = [1, 2, 3];



_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3
 
// 使用ES6改写 
const [last, ...initial] = [1, 2, 3].reverse();

// 或者
const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();
javascript">
function add(a, b) {
  return a + b;
}
var curriedAdd = _.curry(add);
var add2 = curriedAdd(2);
add2(1);
// 3
 
// ES6改写 
const add = a => b => a + b;
const add2 = add(2);
add2(1);
javascript">
var greet = function(greeting, name) {
  return greeting + ' ' + name;
};
 
var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// "hello fred"
 
// ES6改写 
const sayHelloTo = name => greet('hello', name);
sayHelloTo('fred');
// "hello fred"
javascript">_.eq(3, 3);
// true
_.add(10, 1);
// 11
_.map([1, 2, 3], function(n) {
  return _.multiply(n, 10);
});
// [10, 20, 30]
_.reduce([1, 2, 3], _.add);
// 6
 
// ES6改写,箭头函数更简洁简短
 
3 === 3
10 + 1
[1, 2, 3].map(n => n * 10);
[1, 2, 3].reduce((total, n) => total + n);
javascript">
var object = { 'a': 1, 'b': '2', 'c': 3 };
 
return _.pick(object, ['a', 'c']);
// { a: 1, c: 3 }
 
// ES6改写,解构可以达到pick的效果 
const { a, c } = { a: 1, b: 2, c: 3 }; 
return { a, c };
javascript">
_.constant({ 'a': 1 })();
// { a: 1 }
_.identity({ user: 'fred' });
// { user: 'fred' }
_.noop();
// undefined

// es6改写

const constant = x => () => x;
const identity = x => x;
const noop = () => undefined;

// 或者

(() => ({ a: 1 }))();
// { a: 1 }
(x => x)({ user: 'fred' });
// { user: 'fred' }
(() => undefined)();
// undefined

今天我们学习不需要使用的api,学习参考:javascript - 你并不需要Underscore/Lodash - 某熊的全栈之路 - SegmentFault 思否

lodash es6_您可以用ES6取代的10种Lodash功能_dingshi7798的博客-CSDN博客

以上就是今天的学习,关注我,我们一起进步!~


http://www.niftyadmin.cn/n/265677.html

相关文章

被优化了怎么办?他苦学仨月拿到11koffer

网上有个段子叫做“生活就是起起落落落落落落”。人生在世&#xff0c;本就不易&#xff0c;再加上最近大环境影响&#xff0c;各行各业都在内卷&#xff0c;身为芸芸众生的一员&#xff0c;我们也难免受到影响&#xff0c;面临福利裁剪、降薪、甚至被优化的风险。 大环境我们…

全球SPD市场迎来黄金时代,中国领跑全球增长

近日&#xff0c;专注于前沿领域的国际咨询机构ICV发布了全球单光子探测器市场研究报告&#xff0c;报告分析了单光子探测器&#xff08;SPD&#xff09;市场&#xff0c;包括产品定位、下游应用、主要供应商、市场情况和未来趋势等各个方面&#xff0c;以进行分析和预测。 研究…

春招网申简历填写三技巧

网申第一关很重要&#xff0c;不夸张的说网申决定了你的笔试机会&#xff0c;从如信银行考试中心了解到&#xff0c;银行网申筛选过程中&#xff0c;有机器筛选人工筛选两道程序&#xff0c;掌握填写技巧后对提升简历通过率有较大帮助&#xff0c;一定要把握住&#xff0c;关于…

Linux:《gzip》《bzip2》压缩解压

先准备4个文件 1.文件压缩 使用gzip和bzip进行压缩 gzip text1.txt 使用gzip对text1.txt压缩 gzip -9 text2.txt -9是高压缩 由于我使用的文件太小了&#xff0c;所以体现不出来 bzip2 text3.txt 使用bzip2对text3.txt压缩 bzip2 -9 text4.txt -9同样是bzip2的高压缩 2.解压文件…

【论文阅读-ICSE2023】预训练目标对代码相关任务的影响

目录 简介有哪些预训练预训练的影响回答RQ1回答RQ2 总结 简介 Title: Automating Code-Related Tasks Through Transformers: The Impact of Pre-training1 Author: Rosalia Tufano, Luca Pascarella, Gabriele Bavota Published: ICSE2023 Abstract: 尽管现在很多研究能够证…

蓝桥省赛 包子凑数 完全背包

&#x1f351; 算法题解专栏 &#x1f351; 洛谷 P8646 包子凑数 [蓝桥杯 2017 省 AB] 包子凑数 题目描述 小明几乎每天早晨都会在一家包子铺吃早餐。他发现这家包子铺有 N N N 种蒸笼&#xff0c;其中第 i i i 种蒸笼恰好能放 A i A_i Ai​ 个包子。每种蒸笼都有非常多笼…

mysql 索引失效、联合索引失效场景和举例

索引失效 假设有一张user 表&#xff0c;表中包含索引 (id); (name); (birthday); (name,age); 对索引字段进行函数操作 select name from user where year(birthday) 2000;使用模糊查询&#xff0c;查询中使用通配符 select name from user where name like %益达%;使用i…

Java父类强制转换为子类的三种情况(推荐)

Java父类强制转换为子类和子类转父类有三种情况 1.父类对象强转成子类 出错 Father f new Father(); Son s (Son)f;//出错 ClassCastException 2.父类引用子类对象强转成子类 可以 Father f new Son(); Son s (Son)f;//可以 f只能用父类的方法 s可以用子类的所有方法 …