Skip to content

大前端模拟面试 - 2019-12-14

  • 时间: 2019-12-14
  • 候选人: @老沙 from 微信群

题目

1. 实现 Promise.prototype.allSettled

语法: Promise.allSettled(iterable); 其中 iterable 是一个可迭代的对象,例如 Array,其中每个成员都是 Promise。 不同于 Promise.prototype.all, 其不管 resolve 还是 reject,最后的回调函数都会执行。

说明: 候选人可以选择 ts 或者 js 实现,当然用纯碎的 ts 实现可以加分。

ts
if (Promise.prototype.allSettled === void 0) {
  // ts
  Promise.prototype.allSettled = function<T>(ps: Promise<T>[]): Promise<T>[] {
    return ps;
  };
  // js
  Promise.prototype.allSettled = ps => {
    return ps;
  };
}
if (Promise.prototype.allSettled === void 0) {
  // ts
  Promise.prototype.allSettled = function<T>(ps: Promise<T>[]): Promise<T>[] {
    return ps;
  };
  // js
  Promise.prototype.allSettled = ps => {
    return ps;
  };
}

2. 优化代码

如何优化这个代码?

提示:

  1. 从各种角度进行优化
  2. 比如可维护性,可测试性,性能,兼容性等角度
html
<template>
  <div>
    <button id="btn">点我复制</button>
  </div>
</template>

<script>
  export default {
    methods() {
      const btn = document.querySelector("#btn");
      btn.addEventListener("click", () => {
        const input = document.createElement("input");
        document.body.appendChild(input);
        input.setAttribute("value", "你想让用户复制到剪贴板的内容");
        input.select();
        if (document.execCommand("copy")) {
          document.execCommand("copy");
          console.log("复制成功");
        }
        document.body.removeChild(input);
      });
    }
  };
</script>
<template>
  <div>
    <button id="btn">点我复制</button>
  </div>
</template>

<script>
  export default {
    methods() {
      const btn = document.querySelector("#btn");
      btn.addEventListener("click", () => {
        const input = document.createElement("input");
        document.body.appendChild(input);
        input.setAttribute("value", "你想让用户复制到剪贴板的内容");
        input.select();
        if (document.execCommand("copy")) {
          document.execCommand("copy");
          console.log("复制成功");
        }
        document.body.removeChild(input);
      });
    }
  };
</script>

3. 如何应对运营商劫持

如下,运营商可能往你的 html 中注入脚本,也可能修改你的脚本内容。 如何定位和解决问题。

html
<html>
  <!-- 一种是增加一个js -->
  <script src="http://your-site.js"></script>
  <script src="http://not-your-site.js"></script>

  <!-- 一种是修改你的js -->
  <script src="http://your-modified-site.js"></script>
</html>
<html>
  <!-- 一种是增加一个js -->
  <script src="http://your-site.js"></script>
  <script src="http://not-your-site.js"></script>

  <!-- 一种是修改你的js -->
  <script src="http://your-modified-site.js"></script>
</html>

4. CDN 的作用和原理

我们平时都会用到 CDN,不管是自建还是用现有的 CDN 服务商。那么 CDN 给我们带来了什么样的好处,它是做到的呢?

视频

地址:https://www.bilibili.com/video/av79269711/