gpt4 book ai didi

javascript - 重复字符串 - Javascript

转载 作者:IT老高 更新时间:2023-10-28 13:12:03 26 4
gpt4 key购买 nike

返回重复任意次数的字符串的最佳或最简洁的方法是什么?

以下是我迄今为止最好的镜头:

function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}

最佳答案

Note to new readers: This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get String things done. When I wrote "less process" I definitely meant "less code" because, as others have noted in subsequent answers, it performs like a pig. So don't use it if speed matters to you.

我会直接把这个函数放到 String 对象上。与其创建一个数组,填充它,然后用一个空字符连接它,只需创建一个适当长度的数组,然后用你想要的字符串连接它。相同的结果,更少的过程!

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

alert( "string to repeat\n".repeat( 4 ) );

关于javascript - 重复字符串 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/202605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com