【问题标题】:What is the advantage of using _.toLower from lodash instead of Javascript's toLowerCase()?使用 lodash 中的 _.toLower 而不是 Javascript 的 toLowerCase() 有什么好处?
【发布时间】:2021-08-25 04:11:49
【问题描述】:

我在代码库中工作,我看到他们使用的是lodash's _.toLower method 而不是Javascript's built in .toLowerCase() method(除了在整个代码中散布的一堆其他 lodash 实用程序方法之外)。我想知道 lodash 是否提供了任何优势/原因,而不仅仅是使用已经内置在 Javascript 中的方法?

【问题讨论】:

  • undefinednull 不会在 lodash 中造成任何问题
  • 为什么不向从事代码库工作的人提出这个问题?

标签: javascript string lodash


【解决方案1】:

我能看到的唯一可能的“好处”(实际上并不是一个 IMO)是 toLower 也是 callable on non-strings

console.log(_.toLower(
  { foo: 'foo' }
));

console.log(_.toLower(
  { toString() { return 'foo' }}
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

(我更愿意在严肃的代码库中使用 TypeScript 来实现类型安全,并使用内置的 toLowerCase

【讨论】:

    【解决方案2】:

    查看源代码,它似乎处理了一些边缘情况。
    _.toLower 调用 toString(),它本身调用 baseToString()。这是实现大多数有趣功能的地方。

    下面的 sn-p 列出了这些功能:

    // null & undefined is converted to empty string
    test(null);
    test(undefined);
    // correctly identifies -0
    test(-0); // StackSnippet's console also has trouble rendering -0
    // Arrays are traversed and baseToString is called recursively
    // note that here `null` is converted to `"null"`
    test(["AAA", null, -0]); // StackSnippet's console also has trouble rendering -0
    // Symbols in Array works fine
    test([Symbol("FOO")]); // StackSnippet's console also has trouble rendering this
    
    function test(value) {
      console.log(value);
      console.log("_:", _.toLower(value));
      try {
        console.log("native:", value.toString().toLowerCase());
      }
      catch(err) {
        console.log("native failed");
      }
      console.log("#".repeat(20));
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 2022-08-03
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2012-07-16
      相关资源
      最近更新 更多