你不需要 Lodash 或 Underscore - 用 JavaScript 原生函数替代
Lodash 和 Underscore 是两款非常流利的 JavaScript 工具库,广泛的被程序员用于 WEB 前端开发。然而,如果你使用的是现代浏览器,你会发现,有很多的方法、函数实际是可以使用原生的 JavaScript 函数代替,这要感谢 ECMAScript5 [ES5]和 ECMAScript2015 [ES6]。如果你希望你的项目能有更少的依赖,而且你使用的是现代浏览器,那么,使用下面介绍的方法,你完全不再需要 Lodash/Underscore 等使用多年的 JavaScript 工具库。
需要注意的是,下面的代码例子只是用来展示如何用原生的 JavaScript 函数替代 Lodash/Underscore 里的函数执行等效的任务,但 Lodash/Underscore 可能会提供更丰富的功能特性,所以,不要 1:1 的比较它们。
Array
_.concat
Creates a new array concatenating array with any additional arrays and/or values.
// Lodash 和 Underscore 方法 var array = [1] var other = _.concat(array, 2, [3], [[4]]) console.log(other) // 输出: [1, 2, 3, [4]] // JavaScript 原生方法实现 var array = [1] var other = array.concat(2, [3], [[4]]) console.log(other) // 输出: [1, 2, 3, [4]]
浏览器支持情况
1.0 ✔ | 1.0 ✔ | 5.5 ✔ | ✔ | ✔ |
_.fill
Fills elements of array with value from start up to, but not including, end. Note that fill
is a mutable method in both native and Lodash/Underscore.
// Lodash 和 Underscore 方法 var array = [1, 2, 3] _.fill(array, 'a') console.log(array) // 输出: ['a', 'a', 'a'] _.fill(Array(3), 2) // 输出: [2, 2, 2] _.fill([4, 6, 8, 10], '*', 1, 3) // 输出: [4, '*', '*', 10] // JavaScript 原生方法实现 var array = [1, 2, 3] array.fill('a') console.log(array) // 输出: ['a', 'a', 'a'] Array(3).fill(2) // 输出: [2, 2, 2] [4, 6, 8, 10].fill('*', 1, 3) // 输出: [4, '*', '*', 10]
浏览器支持情况
45.0 | 31.0 ✔ | Not supported | Not supported | 7.1 |
_.find
Returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.
// Lodash 和 Underscore 方法 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; }) // 输出: object for 'barney' // JavaScript 原生方法实现 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; }) // 输出: object for 'barney'
浏览器支持情况
45.0 | 25.0 ✔ | Not supported | Not supported | 7.1 |
_.findIndex
Returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.
// Lodash 和 Underscore 方法 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) // 输出: 1 // JavaScript 原生方法实现 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) // 输出: 1
浏览器支持情况
45.0 | 25.0 ✔ | Not supported | Not supported | 7.1 |
_.indexOf
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
// Lodash 和 Underscore 方法 var array = [2, 9, 9] var result = _.indexOf(array, 2) console.log(result) // 输出: 0 // JavaScript 原生方法实现 var array = [2, 9, 9] var result = array.indexOf(2) console.log(result) // 输出: 0
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
_.join
Lodash only
Joins a list of elements in an array with a given separator.
// Lodash 和 Underscore 方法 var result = _.join(['one', 'two', 'three'], '--') console.log(result) // 输出: 'one--two--three' // JavaScript 原生方法实现 var result = ['one', 'two', 'three'].join('--') console.log(result) // 输出: 'one--two--three'
浏览器支持情况
1.0✔ | 1.0✔ | 5.5✔ | ✔ | ✔ |
_.lastIndexOf
Returns the index of the last occurrence of value in the array, or -1 if value is not present.
// Lodash 和 Underscore 方法 var array = [2, 9, 9, 4, 3, 6] var result = _.lastIndexOf(array, 9) console.log(result) // 输出: 2 // JavaScript 原生方法实现 var array = [2, 9, 9, 4, 3, 6] var result = array.lastIndexOf(9) console.log(result) // 输出: 2
浏览器支持情况
✔ | ✔ | 9 ✔ | ✔ | ✔ |
_.reverse
Lodash only
Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.
// Lodash 和 Underscore 方法 var array = [1, 2, 3] console.log(_.reverse(array)) // 输出: [3, 2, 1] // JavaScript 原生方法实现 var array = [1, 2, 3] console.log(array.reverse()) // 输出: [3, 2, 1]
Voice from the Lodash author:
Lodash's
_.reverse
just callsArray#reverse
and enables composition like_.map(arrays, _.reverse).
It's exposed on _ because previously, likeUnderscore
, it was only exposed in the chaining syntax. --- jdalton
浏览器支持情况
1.0✔ | 1.0✔ | 5.5✔ | ✔ | ✔ |
Collection*
Important: Note that the native equivalents are array methods, and will not work with objects. If this functionality is needed, then Lodash/Underscore is the better option.
_.each
Iterates over a list of elements, yielding each in turn to an iteratee function.
// Lodash 和 Underscore 方法 _.each([1, 2, 3], function (value, index) { console.log(value) }) // 输出: 1 2 3 // JavaScript 原生方法实现 [1, 2, 3].forEach(function (value, index) { console.log(value) }) // 输出: 1 2 3
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
_.every
Tests whether all elements in the array pass the test implemented by the provided function.
// Lodash 和 Underscore 方法 function isLargerThanTen (element, index, array) { return element >= 10 } var array = [10, 20, 30] var result = _.every(array, isLargerThanTen) console.log(result) // 输出: true // JavaScript 原生方法实现 function isLargerThanTen (element, index, array) { return element >= 10 } var array = [10, 20, 30] var result = array.every(isLargerThanTen) console.log(result) // 输出: true
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
_.filter
Creates a new array with all elements that pass the test implemented by the provided function.
// Lodash 和 Underscore 方法 function isBigEnough (value) { return value >= 10 } var array = [12, 5, 8, 130, 44] var filtered = _.filter(array, isBigEnough) console.log(filtered) // 输出: [12, 130, 44] // JavaScript 原生方法实现 function isBigEnough (value) { return value >= 10 } var array = [12, 5, 8, 130, 44] var filtered = array.filter(isBigEnough) console.log(filtered) // 输出: [12, 130, 44]
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
_.includes
Checks if value is in collection.
var array = [1, 2, 3] // Lodash 和 Underscore 方法 - also called with _.contains _.includes(array, 1) // 输出: true // JavaScript 原生方法实现 var array = [1, 2, 3] array.includes(1) // 输出: true // JavaScript 原生方法实现 (only works with flat array values, no complex objects) var array = [1, 2, 3] array.indexOf(1) > -1 // 输出: true
浏览器支持情况 for array.includes
47✔ | 43 ✔ | Not supported | 34 | 9 |
浏览器支持情况 for array.indexOf
✔ | ✔ | ✔ | ✔ | ✔ |
_.map
Translate all items in an array or object to new array of items.
// Lodash 和 Underscore 方法 var array1 = [1, 2, 3] var array2 = _.map(array1, function (value, index) { return value * 2 }) console.log(array2) // 输出: [2, 4, 6] // JavaScript 原生方法实现 var array1 = [1, 2, 3] var array2 = array1.map(function (value, index) { return value * 2 }) console.log(array2) // 输出: [2, 4, 6]
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
_.reduce
Applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
// Lodash 和 Underscore 方法 var array = [0, 1, 2, 3, 4] var result = _.reduce(array, function (previousValue, currentValue, currentIndex, array) { return previousValue + currentValue }) console.log(result) // 输出: 10 // JavaScript 原生方法实现 var array = [0, 1, 2, 3, 4] var result = array.reduce(function (previousValue, currentValue, currentIndex, array) { return previousValue + currentValue }) console.log(result) // 输出: 10
浏览器支持情况
✔ | 3.0 ✔ | 9 ✔ | 10.5 | 4.0 |
_.reduceRight
This method is like _.reduce except that it iterates over elements of collection from right to left.
// Lodash 和 Underscore 方法 var array = [0, 1, 2, 3, 4] var result = _.reduceRight(array, function (previousValue, currentValue, currentIndex, array) { return previousValue - currentValue }) console.log(result) // 输出: -2 // JavaScript 原生方法实现 var array = [0, 1, 2, 3, 4] var result = array.reduceRight(function (previousValue, currentValue, currentIndex, array) { return previousValue - currentValue }) console.log(result) // 输出: -2
浏览器支持情况
✔ | 3.0 ✔ | 9 ✔ | 10.5 | 4.0 |
_.size
Return the number of values in the collection.
// Lodash 和 Underscore 方法 var result = _.size({one: 1, two: 2, three: 3}) console.log(result) // 输出: 3 // JavaScript 原生方法实现 var result2 = Object.keys({one: 1, two: 2, three: 3}).length console.log(result2) // 输出: 3
浏览器支持情况
5✔ | 4.0 ✔ | 9 | 12 | 5 |
_.some
Tests whether some element in the array passes the test implemented by the provided function.
// Lodash 和 Underscore 方法 function isLargerThanTen (element, index, array) { return element >= 10 } var array = [10, 9, 8] var result = _.some(array, isLargerThanTen) console.log(result) // 输出: true // JavaScript 原生方法实现 function isLargerThanTen (element, index, array) { return element >= 10 } var array = [10, 9, 8] var result = array.some(isLargerThanTen) console.log(result) // 输出: true
浏览器支持情况
✔ | 1.5 ✔ | 9 ✔ | ✔ | ✔ |
Function
_.after
Note this is an alternative implementation
Creates a version of the function that will only be run after first being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.
var notes = ['profile', 'settings'] // Lodash 和 Underscore 方法 var renderNotes = _.after(notes.length, render) notes.forEach(function (note) { console.log(note) renderNotes() }) // JavaScript 原生方法实现 notes.forEach(function (note, index) { console.log(note) if (notes.length === (index + 1)) { render() } })
浏览器支持情况
✔ | ✔ | ✔ | ✔ | ✔ |
Lang
_.isNaN
Checks if value is NaN.
// Lodash 和 Underscore 方法 console.log(_.isNaN(NaN)) // 输出: true // JavaScript 原生方法实现 console.log(isNaN(NaN)) // 输出: true // ES6 console.log(Number.isNaN(NaN)) // 输出: true
MDN:
In comparison to the global
isNaN()
function,Number.isNaN()
doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert toNaN
, but aren't actually the same value asNaN
. This also means that only values of the type number, that are alsoNaN
, return true. Number.isNaN()
Voice from the Lodash author:
Lodash's
_.isNaN
is equiv to ES6Number.isNaN
which is different than the globalisNaN
. --- jdalton
浏览器支持情况 for isNaN
✔ | ✔ | ✔ | ✔ | ✔ |
浏览器支持情况 for Number.isNaN
25 | 15 | Not supported | ✔ | 9 |
Object
_.assign
The method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
// Underscore: _.extendOwn // Lodash 和 Underscore 方法 function Foo() { this.c = 3; } function Bar() { this.e = 5; } Foo.prototype.d = 4; Bar.prototype.f = 6; var result = _.assign(new Foo, new Bar); console.log(result); // 输出: { 'c': 3, 'e': 5 } // JavaScript 原生方法实现 function Foo() { this.c = 3; } function Bar() { this.e = 5; } Foo.prototype.d = 4; Bar.prototype.f = 6; var result = Object.assign(new Foo, new Bar); console.log(result); // 输出: { 'c': 3, 'e': 5 }
浏览器支持情况
45✔ | 34✔ | No support | 32✔ | 9✔ |
_.keys
Retrieve all the names of the object's own enumerable properties.
// Lodash 和 Underscore 方法 var result = _.keys({one: 1, two: 2, three: 3}) console.log(result) // 输出: ["one", "two", "three"] // JavaScript 原生方法实现 var result2 = Object.keys({one: 1, two: 2, three: 3}) console.log(result2) // 输出: ["one", "two", "three"]
浏览器支持情况
5✔ | 4.0 ✔ | 9 | 12 | 5 |
String
_.repeat
Lodash only
Repeats the given string n times.
// Lodash 和 Underscore 方法 var result = _.repeat('abc', 2) // 输出: 'abcabc' // JavaScript 原生方法实现 var result = 'abc'.repeat(2) console.log(result) // 输出: 'abcabc'
浏览器支持情况
41✔ | 24✔ | Not supported | Not supported | 9 |
_.toLower
Lodash only
Lowercase a given string.
// Lodash 和 Underscore 方法 var result = _.toLower('FOOBAR') console.log(result) // 输出: 'foobar' // JavaScript 原生方法实现 var result = 'FOOBAR'.toLowerCase() console.log(result) // 输出: 'foobar'
浏览器支持情况
✔ | ✔ | ✔ | ✔ | ✔ |
_.toUpper
Lodash only
Uppercase a given string.
// Lodash 和 Underscore 方法 var result = _.toUpper('foobar') console.log(result) // 输出: 'FOOBAR' // JavaScript 原生方法实现 var result = 'foobar'.toUpperCase() console.log(result) // 输出: 'FOOBAR'
浏览器支持情况
✔ | ✔ | ✔ | ✔ | ✔ |
_.trim
Lodash only
Removes leading and trailing whitespace characters from string.
// Lodash 和 Underscore 方法 var result = _.trim(' abc ') console.log(result) // 输出: 'abc' // JavaScript 原生方法实现 var result = ' abc '.trim() console.log(result) // 输出: 'abc'
浏览器支持情况
5.0✔ | 3.5✔ | 9.0✔ | 10.5✔ | 5.0✔ |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
上一篇: Android Studio 快捷键
下一篇: 彻底找到 Tomcat 启动速度慢的元凶
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论