20190225

1. 

function fn(num) {
    if(num === 0) return 0;
    if(num === 1) return 1;
    return fn(num - 1) + fn(num -2)
}

计算 fn(5) + fn(8)

把上述递归转为循环

function fn(num) {
    if(num === 0) return 0;
    if(num === 1) return 1;
    let a = 1, b = 0;
    for(let i = 2; i <= num; i++) {
        let temp = a + b;
        b = a;
        a = temp;
        console.log(a, b, temp)
    }
    return a;
}

2. 打印出数组 [1,5,2,3,2,4] 两元素相加为3的元素:(面试的时候说是向后匹配)

function fn(arr, sum) {
    let i = 0;
    let len = arr.length;
    while(i < arr.length-1) {
        for(let n = i+1; n < len; n++) {
            if((arr[n]+arr[i])==sum) console.log(arr[i], arr[n]);
        }
        ++i;
    }
}

把上述代码精简,毕竟如果要算三数相加就要有三个循环了;

function fn(arr, sum) {
    for(let i = 0; i < arr.length; i++) {
        let index = arr.slice(i).indexOf(sum-arr[i])
if(index != -1) console.log(arr[i], arr[index]);
    }
}

3. koa 写一个传文件的接口 flie/* , 不能用fs的同步方法,如果没有该文件返回404;

// 大概思路
const mime = require('mime'); app.use(async (ctx, next) => { let {path} = ctx.request; if (await fs.exists(path)){ ctx.response.type = mime.lookup(path); return ctx.body = await fs.readFile(path); }else {
return ctx.response.status = 404;
}) })

 

posted @ 2019-02-26 14:14  章鱼樟  阅读(177)  评论(0编辑  收藏  举报