javascript 如何创建一个包含 n 个字符的字符串?如何创建具有特定长度的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16885297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:21:49  来源:igfitidea点击:

How to create a string with n characters? How to create a string with specific length?

javascriptstring

提问by Victor Lyuboslavsky

I'm writing JavaScript unit tests and I need to create a string of length 65536. What's the best way to do this in JavaScript?

我正在编写 JavaScript 单元测试,我需要创建一个长度为 65536 的字符串。在 JavaScript 中执行此操作的最佳方法是什么?

Currently I'm using:

目前我正在使用:

var myString = '';
for (var i = 0; i <= 65535; ++i) {
    myString += 'x';
}

回答by aztek

How about

怎么样

Array(65537).join('x')

Note, that it's 65537, not 65536, because you put characters inbetween.

请注意,它是 65537,而不是 65536,因为您将字符放在它们之间。

回答by aztek

This is a forward-looking answer, and won't work in current implementations.

这是一个前瞻性的答案,在当前的实现中不起作用。

ECMAScript 6 is currently defining a String.prototype.repeatmethod. This will allow you to do:

ECMAScript 6 目前正在定义一个String.prototype.repeat方法。这将允许您执行以下操作:

var result = "x".repeat(65535);

Again, this is a future addition. Currently ECMAScript 6 (Harmony) is being drafted, and this could technically be removed, though it doesn't seem likely.

同样,这是未来的补充。目前 ECMAScript 6 (Harmony) 正在起草中,从技术上讲可以将其删除,尽管看起来不太可能。

Current draft:

当前草稿:

15.5.4.21 String.prototype.repeat (count)

The following steps are taken:

  1. Let Obe CheckObjectCoercible(this value).
  2. Let Sbe ToString(O).
  3. ReturnIfAbrupt(S).
  4. Let nbe the result of calling ToInteger(count).
  5. ReturnIfAbrupt(n).
  6. If n < 0, then throw a RangeError exception.
  7. If nis +Infinity, then throw a RangeError exception.
  8. Let Tbe a Stringvalue that is made from ncopies of Sappended together. If nis 0, Tis the empty String.
  9. Return T.

NOTE 1 This method creates a String consisting of the string elements of this object (converted to String) repeated count time.

NOTE 2 The repeat function is intentionally generic; it does not require that its this value be a String object.Therefore, it can be transferred to other kinds of objects for use as a method.

15.5.4.21 String.prototype.repeat(计数)

采取以下步骤:

  1. 我们OCheckObjectCoercible(this value)
  2. 我们SToString(O)
  3. ReturnIfAbrupt(S).
  4. n是调用的结果ToInteger(count)
  5. ReturnIfAbrupt(n).
  6. 如果n < 0,则抛出 RangeError 异常。
  7. 如果n+Infinity,则抛出 RangeError 异常。
  8. T是一个String由附加在一起的n副本组成的值S。如果n0T则是空字符串。
  9. 返回T

注意 1 此方法创建一个字符串,该字符串由该对象的字符串元素(转换为字符串)重复计数时间组成。

注 2:重复功能是有意通用的;它不要求它的 this 值是一个 String 对象。因此,它可以转移到其他类型的对象作为方法使用。

回答by Paul S.

Array.prototype.joindoesn't have to be called on an Array, just an Objectwith a lengthproperty (tested in Google Chrome, FireFox, IE10)

Array.prototype.join不必在Array上调用,只需一个具有长度属性的对象(在 Google Chrome、FireFox、IE10 中测试)

function makeStr(len, char) {
    return Array.prototype.join.call({length: (len || -1) + 1}, char || 'x');
}
makeStr(5); // "xxxxx"

This lets you benefit from native function making the string, without the overhead of a huge array.

这使您可以从生成字符串的本机函数中受益,而无需庞大数组的开销。

回答by cbley

Out of interest, I created a quick benchmark test on jsperf.com:

出于兴趣,我在 jsperf.com 上创建了一个快速基准测试:

http://jsperf.com/mkstring

http://jsperf.com/mkstring

Contestants are

参赛者是

  1. Array(x).join()

  2. Array.prototype.join posted by Paul S.

  3. strRepeat from underscore.string

  1. 数组(x).join()

  2. Array.prototype.join 由 Paul S 发布。

  3. 来自underscore.string 的strRepeat

function strRepeat(str, qty) {
  if (qty < 1) return '';
  var result = '';
  while (qty > 0) {
    if (qty & 1) result += str;
    qty >>= 1, str += str;
  }
  return result;
}

strRepeat('*', 20000);

  1. EMCAScript 6 String.repeat mentioned by Crayz Train
  1. Crayz Train 提到的 EMCAScript 6 String.repeat

For Firefox 34 (which already supports the ECMAScript6 String.repeat), the native repeat is the fastest, followed by strRepeat.

对于 Firefox 34(已经支持 ECMAScript6 String.repeat),原生的重复是最快的,其次是 strRepeat。

Interestingly with Chrom(e|ium) 39 the strRepeat function is even faster compared to the native String.repeat function of Firefox in my test runs.

有趣的是,在我的测试运行中,与 Firefox 的原生 String.repeat 函数相比,Chrom(e|ium) 39 的 strRepeat 函数甚至更快。

For all tested browsers, the function proposed by Paul S. using the native Array.join method is slower than the strRepeat function of the underscore.string library. So, don't use it if you're looking for a fast method.

对于所有经过测试的浏览器,Paul S. 提出的使用原生 Array.join 方法的函数比 underscore.string 库的 strRepeat 函数慢。因此,如果您正在寻找快速方法,请不要使用它。

回答by aaronman

You could create an array of length whatver you want and then use the join()method on the array which will make it into a string. Array(number).join(char)this creates an array on size number -1. Also note that you do not want to use your method because concatenating strings is very expensive(O(n) every concat). I am not sure if javascript has a StringBuilder like java

您可以创建一个任意长度的数组,然后join()在数组上使用该方法将其变成一个字符串。Array(number).join(char)这会在 size 上创建一个数组number -1。另请注意,您不想使用您的方法,因为连接字符串非常昂贵(O(n) 每个连接)。我不确定 javascript 是否有像 java 这样的 StringBuilder