- 考闭包的
function fun(n,o) {
console.log(o)
return {
fun:function(m){
return fun(m,n);
}
};
}
var a = fun(0); a.fun(1); a.fun(2); a.fun(3);//undefined,?,?,?
var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
var c = fun(0).fun(1); c.fun(2); c.fun(3);//undefined,?,?,?
//问:三行a,b,c的输出分别是什么?
//答案:
//a: undefined,0,0,0
//b: undefined,0,1,2
//c: undefined,0,1,1
- 大数相加
let a = '9007199254740991'
let b = '1234567899999999999'
function add(a, b) {
//取两个数字的最大长度
let maxLength = Math.max(a.length, b.length)
//用0去补齐长度
a = a.padStart(maxLength, 0) //"0009007199254740991"
b = b.padStart(maxLength, 0) //"1234567899999999999"
//定义加法过程中需要用到的变量
let t = 0
let f = 0 //"进位"
let sum = ''
for (let i = maxLength - 1; i >= 0; i--) {
t = parseInt(a[i]) + parseInt(b[i]) + f
f = Math.floor(t / 10)
sum = (t % 10) + sum
}
if (f == 1) {
sum = '1' + sum
}
return sum
}