문제

Perl에서는 구문을 사용하여 문자를 여러 번 반복 할 수 있습니다.

$a = "a" x 10; // results in "aaaaaaaaaa"

JavaScript에서 이것을 달성하는 간단한 방법이 있습니까? 나는 분명히 함수를 사용할 수 있지만 접근 방식이 내장되어 있는지 또는 다른 영리한 기술이 있는지 궁금합니다.

도움이 되었습니까?

해결책

요즘 repeat 문자열 방법 구현되었습니다 거의 어디에나. (그것은이다 인터넷 익스플로러가 아닙니다.) 따라서 이전 브라우저를 지원하지 않으면 간단히 쓸 수 있습니다.

"a".repeat(10)

전에 repeat, 우리는이 해킹을 사용했습니다.

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"

(길이 11의 배열은 당신에게 10 "a"만으로도 얻습니다. Array.join 논쟁을한다 ~ 사이 배열 요소.)

Simon은 또한이를 지적합니다 이 jsperf, Safari와 Chrome (Firefox는 아님)에서는 For Loop (약간 덜 간결하지만)를 사용하여 간단히 추가하여 문자를 여러 번 반복하는 것이 더 빠릅니다.

다른 팁

새로운 ES6 Harmony에서는이 작업을 수행하는 기본 방법을 가질 것입니다. 반복하다. 또한 ES6은 지금만 실험적입니다.이 기능은 다음과 같습니다. 이미 사용 가능합니다 가장자리, FF, Chrome 및 Safari

"abc".repeat(3) // "abcabcabc"

반복 기능을 사용할 수없는 경우 옛날 영을 사용할 수 있습니다. Array(n + 1).join("abc")

자신을 많이 반복하면 편리합니다.

String.prototype.repeat = String.prototype.repeat || function(n){
  n= n || 1;
  return Array(n+1).join(this);
}

alert(  'Are we there yet?\nNo.\n'.repeat(10)  )

가장 성능이 뛰어난 방법은입니다 https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/repeat

짧은 버전은 다음과 같습니다.

  String.prototype.repeat = function(count) {
    if (count < 1) return '';
    var result = '', pattern = this.valueOf();
    while (count > 1) {
      if (count & 1) result += pattern;
      count >>>= 1, pattern += pattern;
    }
    return result + pattern;
  };
  var a = "a";
  console.debug(a.repeat(10));

Mozilla의 Polyfill :

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (;;) {
      if ((count & 1) == 1) {
        rpt += str;
      }
      count >>>= 1;
      if (count == 0) {
        break;
      }
      str += str;
    }
    // Could we try:
    // return Array(count + 1).join(this);
    return rpt;
  }
}

대안은 다음과 같습니다.

for(var word = ''; word.length < 10; word += 'a'){}

여러 숯을 반복 해야하는 경우 조건부를 곱하십시오.

for(var word = ''; word.length < 10 * 3; word += 'foo'){}

노트: 당신은 word = Array(11).join('a')

프로젝트에 라이브러리를 포함시키는 것에 반대하지 않는 경우 Lodash는 반복 기능을 가지고 있습니다.

_.repeat('*', 3);
// → '***

https://lodash.com/docs#repeat

모든 브라우저

다음 함수는 허용 된 답변에서 제안 된 옵션보다 훨씬 빠르게 수행됩니다.

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i < count;)
        array[i++] = str;
    return array.join('');
}

당신은 이것을 사용합니다 :

var repeatedString = repeat("a", 10);

이 기능의 성능을 허용 된 답변에서 제안한 옵션의 성능과 비교하려면 이 바이올린 그리고 이 바이올린 벤치 마크.

현대식 브라우저 만

최신 브라우저에서는 이제이 작업을 수행 할 수 있습니다. String.prototype.repeat 방법:

var repeatedString = "a".repeat(10);

이 방법에 대해 자세히 알아보십시오 MDN.

이 옵션은 훨씬 빠릅니다. 불행히도 인터넷 익스플로러 버전에서는 작동하지 않습니다. 테이블의 숫자는 메소드를 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.

enter image description here

Array(10).fill('a').join('')

가장 투표 된 답변은 조금 더 작지만이 접근 방식을 사용하면 추가 배열 항목을 추가 할 필요가 없습니다.

/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);

ES2015/ES6에서 사용할 수 있습니다 "*".repeat(n)

따라서 이것을 프로젝트에 추가하면 좋습니다.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };

또 다른 흥미로운 방법 빠르게 반복 n 문자는 빠른 지수화 알고리즘에서 아이디어를 사용하는 것입니다.

var repeatString = function(string, n) {
    var result = '', i;

    for (i = 1; i <= n; i *= 2) {
        if ((n & i) === i) {
            result += string;
        }
        string = string + string;
    }

    return result;
};

내 프로젝트에서 값을 반복하려면 반복을 사용합니다.

예를 들어:

var n = 6;
for (i = 0; i < n; i++) {
    console.log("#".repeat(i+1))
}

그러나이 방법이 ECMAScript 6 사양에 추가되었으므로주의하십시오.

여기에 내가 사용하는 것은 다음과 같습니다.

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }
function repeatString(n, string) {
  var repeat = [];
  repeat.length = n + 1;
  return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,'🌹'); // => "🌹🌹🌹🌹🌹🌹🌹🌹🌹🌹"

나는 확장 할 것이다 @Bonbon의 대답. 그의 방법은 누군가가 그렇게해야 할 경우를 대비하여 "기존 문자열에 n을 부여하는"쉬운 방법입니다. 예를 들어 그 이후로 "Google"은 1이고 100 0이됩니다..

for(var google = '1'; google.length < 1 + 100; google += '0'){}
document.getElementById('el').innerText = google;
<div>This is "a google":</div>
<div id="el"></div>

노트: 원래 문자열의 길이를 조건부에 추가해야합니다.

Lodash 와 유사한 기능을 제공합니다 자바 스크립트 반복 () 모든 브라우저에서 사용할 수없는 함수. 그것은이라고 _.반복하다 버전 3.0.0 이후 제공 :

_.repeat('a', 10);
var stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

var repeatedString = stringRepeat("a", 1);

1 라이너로도 사용할 수 있습니다.

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}

커피 스크립트에서 :

( 'a' for dot in [0..10]).join('')
String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"

다음은 ES6 버전입니다

const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
repeat("A",20).forEach((a,b) => console.log(a,b+1))

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top