簡體   English   中英

使用 Infinity 作為第二個參數調用 String.prototype.substring

[英]Calling String.prototype.substring with Infinity as second parameter

我有一個非常類似於的功能:

 const processString = (input, maxSize = Infinity) => { return input // More 'input' chained transformations (eg .padStart()) .substring(0, maxSize) // More 'input' chained transformations (eg .padStart()) } const assertString = "Lorem ipsum" console.assert(processString(assertString, 5) === "Lorem") console.assert(processString(assertString) === assertString)

雖然這工作正常,但我想知道,使用Infinity作為第二個參數調用String.prototype.substring是否不是一個壞習慣,因為我在文檔的任何地方都找不到它。

我這樣做的原因是我在.substring調用之前和之后有多個鏈式調用,我希望以這種方式保持實現,而不是將其分解為單獨的變量和條件。

我基本上有兩個問題:

  1. 可以用 Infinity 作為第二個參數調用 String.prototype.substring 嗎?
  2. 或者,實現相同結果的不同方式是什么?

最大長度為Math.pow(2, 53) - 1

看看這個: https : //www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types-string-type

String 類型是由零個或多個 16 位無符號整數值(“元素”)組成的所有有序序列的集合,最大長度為 2^53-1 個元素。

您可以將其設置為常量並使用

const MAX_STRING_LENGTH = Math.pow(2, 53) - 1; // 9007199254740991

如果你真的需要第二個參數,我不明白這會是一個糟糕的做法。 我認為可能更健壯的唯一方法是使用input.length

 const processString = (input, maxSize = input.length) => { return input // More 'input' chained transformations (eg .padStart()) .substring(0, maxSize) // More 'input' chained transformations (eg .padStart()) } const assertString = "Lorem ipsum" console.assert(processString(assertString, 5) === "Lorem") console.assert(processString(assertString) === assertString)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM