-
Notifications
You must be signed in to change notification settings - Fork 644
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
字节编程题:实现一个add方法 #103
Comments
先来抛砖,希望可以引玉 function add() {
const args = Array.prototype.slice.apply(arguments);
const self = this;
this.nums = [...args];
function _add() {
const _args = Array.prototype.slice.apply(arguments);
this.nums.push(..._args);
return _add;
}
_add.value = function() {
return self.nums.reduce((acc, cur) => acc += cur, 0);
}
return _add;
} 考验的是闭包和this |
function add(...args) {
const nums = [...args];
function addFn(...args1) {
nums.push(...args1);
return addFn;
}
addFn.value = () => {
const sum = nums.reduce((s, n) => s + n, 0);
console.log(sum);
return sum;
};
return addFn;
} |
思路都差不多 const add = (...args) => {
const _add = (...args1) => {
return add(...args, ...args1)
}
_add.value = () => args.reduce((t, e) => t+e)
return _add
}
add(1)(2,3)(4).value() |
|
|
function add(...params) { return innerAdd; |
/**
* 函数柯里化实现add(1)(1,2)(3)等
* https://blog.csdn.net/weixin_30498807/article/details/102319249
*/
// let obj = {
// name:'hell',
// toString:function() {
// console.log('调用了toString')
// return '22'
// },
// valueOf:function() {
// console.log('调用了obj.valueOf');
// return '00'
// }
// }
// console.log(obj+"3")
function test() {
console.log(1);
}
test.toString = function () {
console.log('调用了valueOf方法');
return 2;
}
function add() {
var arr = Array.prototype.slice.call(arguments)
const _adder = function () {
arr.push(...arguments)
return _adder;
}
_adder.valueOf = function () {
return arr.reduce((a, b) => a + b);
}
return _adder;
}
let res = add(1)(2)(3, 4);
console.log(add(1)(2, 3).valueOf())
console.log(res+0) |
function add(...args1) { _add.value = function () { return _add; |
例如:
The text was updated successfully, but these errors were encountered: