Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript repeats the string


May 09, 2021 CoffeeScript


Table of contents


Repeat the string

Problem

You want to repeat a string.

Solution

Create an array of empty elements, and then stitch the array elements together with the string to be repeated as a connection character:

# 创建包含10个foo的字符串
Array(11).join 'foo'

# => "foofoofoofoofoofoofoofoofoofoo"

Repeat the method for the string

You can also create methods for strings in prototypes. It's simple:

# 为所有的字符串添加重复方法,这会重复返回 n 次字符串
String::repeat = (n) -> Array(n+1).join(this)

Discuss

JavaScript lacks string repeat functions, and CoffeeScript does not provide it. Although list inference (comprehensions) can also be used here, it is easier to build an array of n-1 empty elements like this for simple string repetition, and then stitch it together.