質問

Perlで繰り返し文字を複数回使用の構文:

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

ありが簡単にそのためにはJavascript?私はできることで機能を使用するものかと思っていった他の構築にアプローチ、またはその他の巧みな技です。

他のヒント

新しいES6の調和、ネイティブの方のためにこれ 繰り返し.も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)  )

最もパフォーマンスwiceの方法がある 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のポリフィルます:

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')のように1でオーバーシュートする必要はありません。

あなたのプロジェクトでライブラリを含むと対向していない場合は、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

このオプションは、さらに高速です。残念ながら、それはインターネットエクスプローラのいずれかのバージョンでは動作しません。表中の数字は完全に方法をサポートする最初のブラウザのバージョンを指定します:

" ここに画像の説明を入力する

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,'🌹'); // => "🌹🌹🌹🌹🌹🌹🌹🌹🌹🌹"

私はする@ボンボンの答えの上で展開するつもりです。彼の方法は、誰もがそれを行う必要があるだけの場合には、「既存の文字列にNの文字を追加」する簡単な方法です。例えば、ので、 "グーグル" はの100ゼロに続く1である。

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 の<のhref = "https://developer.mozilla.org/と同様の機能を提供していますEN /ドキュメント/ウェブ/ JavaScriptを/リファレンス/ Global_Objects /文字列/リピート」のrel = "nofollowをnoreferrer"> Javascriptをリピート()すべてのたブラウザでは利用できませんの機能。それが呼ばれる _.repeat と利用でき以来、バージョン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);

あまりにもワンライナーとして使用することができます:

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

のCoffeeScriptでます:

( '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