今天我在求职面试 - 我已经被提交了一个任务。 我从来没有encoutered这样的功能,所以它是:如何用参数触发一个任意函数Javascript
写下一个函数,它触发这样的后:
console.log('hello'.repeatify(3))
回报
hellohellohello
我试图创建一个空对象和追加方法repeatify,但我只是不知道如何触发它只是'你好'。
也许我应该改变console.log方法?
感谢您的帮助:)
今天我在求职面试 - 我已经被提交了一个任务。 我从来没有encoutered这样的功能,所以它是:如何用参数触发一个任意函数Javascript
写下一个函数,它触发这样的后:
console.log('hello'.repeatify(3))
回报
hellohellohello
我试图创建一个空对象和追加方法repeatify,但我只是不知道如何触发它只是'你好'。
也许我应该改变console.log方法?
感谢您的帮助:)
是不是真的很难。您必须为String.prototype
创建新函数,并使用repeat()
函数将给定的字符串乘以给定的参数。
String.prototype.repeatify = function(count){
return this.repeat(count);
};
console.log('hello'.repeatify(3))
您可以为每一个对象自己的原型方法,但你不应该与本地对象做到这一点:
String.prototype.repeatify = function(num) {
return this.repeat(num);
}
console.log('hello'.repeatify(3));
不知道JavaScript字符串上的重复函数。这可能是更好的解决方案。但是为什么他们会要求在面试中重新实现一个已经存在的功能:D – user3691763
呃,谁知道 - 他们可能只是想测试一下,如果你知道这个......但是正如上面所写的和链接的,不要使用该模式位于String,Array等本机对象上... @ user3691763 – baao
String.prototype.repeatify = function(amount)
{
var endString = "";
for(var i = 0; i < amount; ++i)
{
endString += this;
}
return endString;
}
只需修改字符串的原型对象:
String.prototype.repeatify = function (A) {
var i = 1;
var a = this;
while (i++ < A) {
a += this;
}
return a;
}
console.log('hello'.repeatify(3));
// outputs hellohellohello
上有修改的内置对象的原型百感交集。我认为这很好,这是一个不好的做法。我个人试图避免它,并更喜欢定义一个独立的函数来修改我没有创建的东西的原型。
谢谢你,先生! – Pravissimo