我在一次面试中被问到这个问题,我没有解决。我想知道你们谁能帮我。
fn("hello").fn("world").fn("!!!").fn();
function fn (str){
// Enter Solution Here
}
解决方案应该返回'hello world !!'。
我尝试了方法链接,并能够得到一个部分正确的答案,如下所示:
function fn(str) {
var string = str;
this.fn1 = function(str1) {
string += " "+str1;
return this;
}
this.fn = function() {
console.log(string)
}
}
new fn("hello").fn1("world").fn1("!!!").fn();
,但正如你所看到的,我不能让它工作,除非我使用fn1作为连接字符串的函数。如有任何帮助,我将不胜感激。
让函数返回一个具有一个fn
方法的对象。如果,当你调用它时,它有一个参数,更新字符串,否则返回字符串,以便你可以记录它。
function fn(str = '') {
return {
fn: function (s) {
if (s) {
str += ` ${s}`;
return this;
}
return str;
}
};
}
const output = fn('hello').fn('world').fn('!!!').fn();
console.log(output);
附加文档
- 模板/字符串
可以返回具有两个属性的对象,一个用于返回完整字符串,另一个用于收集部分并返回对象。
function fn(str) {
const
fns = {
fn: function () {
return str;
},
fn1: function (s) {
str += ' ' + s;
return fns;
}
};
return fns;
}
console.log(fn("hello").fn1("world").fn1("!!!").fn());
我想这应该能奏效:
function fn(s){
return new function(){
this.str = s;
this.fn = (ns) => {if(ns){this.str += " "+ns; return this;} else return this.str;};
}
}
let a = fn("hello").fn("world").fn("!!!").fn();
console.log(a);
似乎你需要使用对象
const generic = {
"fn1":null,
"current":"",
"fn": () => {
//what do you want to do with "this.current"?
}
}
function fn(str) {
var ret = generic;
ret.fn1 = (wa) =>{
var again = generic;
again.current +=wa;
return again;
}
ret.current += str;
return ret;
}
您可以使用.fn()
方法返回一个对象,该方法将检查是否传入参数,以确定何时终止链或继续链。
如果不发送参数,则简单返回累积的字符串。
否则,再次调用fn()
函数对字符串进行累加,并获得与之前相同结构的下一个副本:
const result = fn("hello").fn("world").fn("!!!").fn();
console.log(result);
function fn (str){
return {
fn(nextString) {
if (nextString === undefined)
return str;
return fn(`${str} ${nextString}`);
}
};
}
由于该操作是不可变的,这意味着链中的每个环节都是独立的,因此分配变量以继续使用不同的链是没有问题的:
const helloWorld = fn("hello").fn("world");
const one = helloWorld.fn("one").fn();
const two = helloWorld.fn("two").fn();
const three = helloWorld.fn("three").fn();
console.log(one);
console.log(two);
console.log(three);
function fn (str){
return {
fn(nextString) {
if (nextString === undefined)
return str;
return fn(`${str} ${nextString}`);
}
};
}