我想打印一个字符串,例如blah
3 次,但我想将该函数链接到该字符串。
我现在这样做:
function repeatMe( number ) {
for (var i = 0; i < number; i++) {
document.write('blah');
}
}
console.log( repeatMe( 3 ) );
但是是否可以像这样调用函数来打印 blah
:
console.log( 'blah'.repeatMe( 3 ) );
最佳答案
通过将 repeatMe
添加到字符串原型(prototype)来返回一个连接的字符串:
String.prototype.repeatMe = function (number) {
var txt = '';
for (var i = 0; i < number; i++) {
txt += this;
}
return txt;
}
var div = document.querySelector('#id');
div.innerHTML = 'blah'.repeatMe(3);
或者:
console.log('blah'.repeatMe(3));
关于javascript - 将函数链接到要打印的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270857/