2020 Q3阿里面试真题

302 阅读2分钟

记录一下;

1. 说出下面输出的值,以及为什么

setTimeout(()=>{
  console.log(1);
  Promise.resolve().then(()=>{
    console.log(2);
  });
  setTimeout(()=>{console.log(5)}, 0)
}, 0)

setTimeout(()=>{
  console.log(3);
  Promise.resolve().then(()=>{
    console.log(4);
  });
}, 0)

// 1
// 2
// 3
// 4
// 5
  1. 如果数组可以分为N个子数组,每个子数组的和相等,输出连续子数组的长度,如果没有输出null
如果数组可以分为N个子数组,每个子数组的和相等,输出连续子数组的长度,如果没有输出null
[1,2,3,2,4,6] 3

[[1,2,3], [2,4], [6]]

function split(arr, n) {
	
}

思路:1. 找到全部的排列组合返回一个二维数组 2. 遍历找到符合题意条件组合

function getGroup(data, index = 0, group = []) {
    const needApply = [];
    needApply.push([data[index]]);

    for (let i = 0; i < group.length; i++) {
        needApply.push([...group[i], data[index]]);
    }

    group.push(...needApply);

    if (index + 1 >= data.length) {
        return group;
    } else {
        return getGroup(data, index + 1, group);
    }
}

function sum(arr) {
    return arr.reduce((acc, val) => acc + val, 0);
}

function split(arr, n) {
    // 获取全排列组合的结果
    const result = getGroup(arr); // [1, 2, 3] => [[1], [2], [1,2], [3], [1,3], [1,2,3]]

    while (result.length) {
        const current = result.shift(); // 头部弹出一个元素
        const number = sum(current); // 求和
        const output = [current]; // 放到第一位
        // 遍历数组匹配到与当前和项一样的就push到output中
        result.forEach((item) => {
            if (sum(item) === number) {
                output.push(item);
            }
        });
        // console.log('output', JSON.stringify(output));

        // 如果找到n个和相等的就退出
        if (output.length === n) {
            return output;
        }
    }
    return null;
}

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const result = split(data, 6);

console.log('result', result);
// result [ [ 1, 3, 4 ], [ 1, 2, 5 ], [ 3, 5 ], [ 2, 6 ], [ 1, 7 ], [ 8 ] ]

3. 协商缓存

4. vue router 实现原理,hash和history模式的区别?

  1. vue-router 默认 hash 模式 —————使用URL的hash来模拟一个完整的URL,于是当URL改变时,页面也不会重新加载。
  2. history模式,利用history.pushState API 来完成URL跳转而无需重新加载页面。
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
  1. 使用history模式,URL就像正常的url,例如:http://yoursite.com/user/id
  2. history模式需要后端配置支持。因为我们的应用是单页面客户端应用, 如果后台没有正确的配置,当用户浏览器直接访问http://yoursite.com/user/id, 就会返回404. 故,需要在服务端增加一个覆盖所有情况的候选资源, 如果URL匹配不到任何静态资源,则应该返回同一个index.html页面, 这个页面也就是你app以来的页面。

后端如何配置?

nginx

location / {
 try_files $uri $uri/ /index.html;
}

原生 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

有不同见解的,欢迎在评论区下留下你的答案