-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第166题:闭包 JS基础 编程题 (字节) #455
Labels
Comments
Function.prototype.getValue = function () {
let num = this.arr.reduce((x, y) => (x + y))
this.arr = null
return num
}
var foo = function (...args) {
if (!Array.isArray(foo.arr)) {
foo.arr = []
}
foo.arr.push(...args)
return foo;
} |
function foo(...args) {
foo.value = args.reduce((total, cur) => total + cur, (foo.value || 0))
return foo
}
foo.getValue = function () {
var value = this.value;
this.value = 0;
return value
} |
function foo(...args) {
const target = (...arg1s) => foo(...[...args, ...arg1s])
target.getValue = () => args.reduce((p, n) => p+ n, 0)
return target
} |
@Ishmael-Yoko 不错,大概跟面试官想要的一致。 |
const foo = function() {
let args = Array.prototype.slice.call(arguments);
const target = function() {
args = args.concat(Array.prototype.slice.call(arguments));
return foo(...args);
};
target.getValue = () => args.reduce((x, y) => x + y, 0);
return target;
}; |
function foo(...args) {
const sum = args.reduce((acc, v) => acc + v, 0);
const hof = function (...args) {
return foo(sum, ...args);
};
hof.getValue = () => sum;
return hof;
} |
const foo = (...args) => {
const _add = (...args1) => {
return foo(...args, ...args1);
}
_add.getValue = () => args.reduce((acc, cur) => acc + cur);
return _add;
} |
Tip:
function foo(...args) {
let addArgs = [...args];
function fn(...innerArgs) {
addArgs = [...addArgs, ...innerArgs];
return fn;
}
fn.getValue = function () {
return addArgs.reduce((pre, cur) => {
return pre + cur;
}, 0);
};
return fn;
}
const sum = foo(1, 2, 3)(2)(3).getValue();
// const sum = foo(1, 2, 3).getValue();
console.log("sum", sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var foo = function(...args) { // 要求实现函数体}
var f1 = foo(1,2,3); f1.getValue(); // 6 输出是参数的和
var f2 = foo(1)(2,3); f2.getValue(); // 6
var f3 = foo(1)(2)(3)(4); f3.getValue(); // 10
The text was updated successfully, but these errors were encountered: