1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js 文字列を指定回数くりかえす

Last updated at Posted at 2016-12-13

##文字列を指定回数くりかえす。負の数の場合は空文字を返す。

script.js
function repeatStringNumTimes(str, num) {
//write your code.
}
repeatStringNumTimes("abc", 3) //"abcabcabc"

出力結果 例

script.js
repeatStringNumTimes("abc", 3) //"abcabcabc"
repeatStringNumTimes("abc", 4) // "abcabcabcabc"
repeatStringNumTimes("abc", 1) // "abc"
repeatStringNumTimes("*", 8) // "********"
repeatStringNumTimes("abc", -2) // ""

##何も考えずに書いたコード

script.js
function repeatStringNumTimes(str, num) {
  var arr = [];
   for(var i = 0; i< num; i++){
     arr.push(str);
   }
  return arr.join("");
}

##工夫したコード

script.js
function repeatStringNumTimes(str, num) {
    return num > 0 ? str.repeat(num) : '';
}

##考え方
numが正の数かどうか判定し、trueならrepeat(num)を返す。
falseなら空文字を返す。

もっと簡潔に美しくかけるよ!という方、コメントお待ちしております。

##参考リンク
repeat()
三項演算子

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?