如何使用Lodash

Tzu Chieh Lin
Aug 31, 2018 · 2 min read

Lodash簡單來說就是擴充或增加Javascript 的 Library,提供更多方法使Javascript運用得更為方便

安裝lodash

npm install lodash<script src="lodash.js"></script>

常用的幾個方法

_.get(object, path, [defaultValue])

var object = { 'a': [{ 'b': { 'c': 3 } }] };_.get(object, 'a[0].b.c');// => 3_.get(object, ['a', '0', 'b', 'c']);// => 3_.get(object, 'a.b.c', 'default');// => 'default'

防止沒資料時回傳undefined,導致JavaScript抱錯

_.has(object, path)

var object = { 'a': { 'b': 2 } };var other = _.create({ 'a': _.create({ 'b': 2 }) });_.has(object, 'a');// => true_.has(object, 'a.b');// => true_.has(object, ['a', 'b']);// => true_.has(other, 'a');// => false

還有很多其他的方法,Lodash 通過 array、number、objects、string 等等的方式讓JavaScript變得更精簡,就可以讓程式碼更簡潔也容易維護。

參考:https://lodash.com/docs/4.17.10

TWJOIN

    Tzu Chieh Lin

    Written by

    TWJOIN

    TWJOIN

    哲煜科技的小夥伴們的文章

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade