CSS 部分

两栏布局

要求:垂直两栏,左边固定右边自适应。

查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. .outer {
  10. height: 100px;
  11. margin-bottom: 10px;
  12. }
  13. .left {
  14. background: tomato;
  15. height: 100px;
  16. }
  17. .right {
  18. background: gold;
  19. height: 100px;
  20. }
  21. /* 浮动 */
  22. .outer1 .left {
  23. width: 200px;
  24. float: left;
  25. }
  26. .outer1 .right {
  27. width: auto;
  28. margin-left: 200px;
  29. }
  30. /* flex */
  31. .outer2 {
  32. display: flex;
  33. }
  34. .outer2 .left {
  35. flex-grow: 0;
  36. flex-shrink: 0;
  37. flex-basis: 200px;
  38. }
  39. .outer2 .right {
  40. flex: auto; /* 1 1 auto */
  41. }
  42. /* position */
  43. .outer3 {
  44. position: relative;
  45. }
  46. .outer3 .left {
  47. position: absolute;
  48. width: 200px;
  49. }
  50. .outer3 .right {
  51. margin-left: 200px;
  52. }
  53. /* position again */
  54. .outer4 {
  55. position: relative;
  56. }
  57. .outer4 .left {
  58. width: 200px;
  59. }
  60. .outer4 .right {
  61. position: absolute;
  62. top: 0;
  63. left: 200px;
  64. right: 0;
  65. }
  66. </style>
  67. </head>
  68. <!-- 左右两栏,左边固定,右边自适应 -->
  69. <body>
  70. <div class="outer outer1">
  71. <div class="left">1-left</div>
  72. <div class="right">1-right</div>
  73. </div>
  74. <div class="outer outer2">
  75. <div class="left">2-left</div>
  76. <div class="right">2-right</div>
  77. </div>
  78. <div class="outer outer3">
  79. <div class="left">3-left</div>
  80. <div class="right">3-right</div>
  81. </div>
  82. <div class="outer outer4">
  83. <div class="left">4-left</div>
  84. <div class="right">4-right</div>
  85. </div>
  86. </body>
  87. </html>
  88. 复制代码

三栏布局

要求:垂直三栏布局,左右两栏宽度固定,中间自适应

查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. .outer, .left, .middle, .right {
  10. height: 100px;
  11. margin-bottom: 5px;
  12. }
  13. .left {
  14. background: tomato;
  15. }
  16. .middle {
  17. background: lightgreen;
  18. }
  19. .right {
  20. background: gold;
  21. }
  22. /* 左右分别设置绝对定位 中间设置外边距 */
  23. .outer1 {
  24. position: relative;
  25. }
  26. .outer1 .left {
  27. position: absolute;
  28. width: 100px;
  29. }
  30. .outer1 .middle {
  31. margin: 0 200px 0 100px;
  32. }
  33. .outer1 .right {
  34. position: absolute;
  35. width: 200px;
  36. top: 0;
  37. right: 0;
  38. }
  39. /* flex 布局 */
  40. .outer2 {
  41. display: flex;
  42. }
  43. .outer2 .left {
  44. flex: 0 0 100px;
  45. }
  46. .outer2 .middle {
  47. flex: auto;
  48. }
  49. .outer2 .right {
  50. flex: 0 0 200px;
  51. }
  52. /* 浮动布局 但是 html 中 middle要放到最后 */
  53. .outer3 .left {
  54. float: left;
  55. width: 100px;
  56. }
  57. .outer3 .right {
  58. float: right;
  59. width: 200px;
  60. }
  61. .outer3 .middle {
  62. margin: 0 200px 0 100px;
  63. }
  64. </style>
  65. </head>
  66. <!-- 三栏布局 左右固定 中间自适应 -->
  67. <body>
  68. <div class="outer outer1">
  69. <div class="left">1-left</div>
  70. <div class="middle">1-middle</div>
  71. <div class="right">1-right</div>
  72. </div>
  73. <div class="outer outer2">
  74. <div class="left">2-left</div>
  75. <div class="middle">2-middle</div>
  76. <div class="right">2-right</div>
  77. </div>
  78. <div class="outer outer3">
  79. <div class="left">3-left</div>
  80. <div class="right">3-right</div>
  81. <div class="middle">3-middle</div>
  82. </div>
  83. </body>
  84. </html>
  85. 复制代码

圣杯布局 和 双飞翼布局

和三栏布局要求相同,不过中间列要写在前面保证优先渲染。

查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. .outer, .left, .middle, .right {
  10. height: 100px;
  11. margin-bottom: 5px;
  12. }
  13. .left {
  14. background: tomato;
  15. }
  16. .middle {
  17. background: lightgreen;
  18. }
  19. .right {
  20. background: gold;
  21. }
  22. /* 圣杯布局 通过浮动和负边距实现 */
  23. .outer1 {
  24. padding: 0 200px 0 100px;
  25. }
  26. .outer1 .middle {
  27. width: 100%;
  28. float: left;
  29. }
  30. .outer1 .left {
  31. width: 100px;
  32. float: left;
  33. margin-left: -100%;
  34. position: relative;
  35. left: -100px;
  36. }
  37. .outer1 .right {
  38. width: 200px;
  39. float: left;
  40. margin-left: -200px;
  41. position: relative;
  42. left: 200px;
  43. }
  44. /* 双飞翼布局 */
  45. .outer2 .middle-wrapper {
  46. width: 100%;
  47. float: left;
  48. }
  49. .outer2 .middle {
  50. margin: 0 200px 0 100px;
  51. }
  52. .outer2 .left {
  53. width: 100px;
  54. float: left;
  55. margin-left: -100%;
  56. }
  57. .outer2 .right {
  58. width: 200px;
  59. float: left;
  60. margin-left: -200px;
  61. }
  62. </style>
  63. </head>
  64. <!-- 三栏布局 左右固定 中间自适应 -->
  65. <body>
  66. <!-- 圣杯布局 middle 最先 -->
  67. <div class="outer outer1">
  68. <div class="middle">圣杯-middle</div>
  69. <div class="left">圣杯-left</div>
  70. <div class="right">圣杯-right</div>
  71. </div>
  72. <!-- 双飞翼布局 middle 最先 多一层 div -->
  73. <div class="outer outer2">
  74. <div class="middle-wrapper">
  75. <div class="middle">双飞翼布局-middle</div>
  76. </div>
  77. <div class="left">双飞翼布局-left</div>
  78. <div class="right">双飞翼布局-right</div>
  79. </div>
  80. </body>
  81. </html>
  82. 复制代码

三角形

实现一个三角形

常见题目,通过 border 实现
查看代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>三角形</title>
  5. <style type="text/css">
  6. .box1, .box2, .box3, .box4 {
  7. height: 0px;
  8. width: 0px;
  9. float: left;
  10. border-style: solid;
  11. margin: 10px;
  12. }
  13. .box1 { /* 等腰直角 */
  14. border-width: 100px;
  15. border-color: tomato transparent transparent transparent;
  16. }
  17. .box2 { /* 等边 */
  18. border-width: 100px 173px;
  19. border-color: transparent tomato transparent transparent;
  20. }
  21. .box3 { /* 等腰 */
  22. border-width: 100px 80px;
  23. border-color: transparent transparent tomato transparent;
  24. }
  25. .box4 { /* 其他 */
  26. border-width: 100px 90px 80px 70px;
  27. border-color: transparent transparent transparent tomato;
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div class="box1"></div>
  33. <div class="box2"></div>
  34. <div class="box3"></div>
  35. <div class="box4"></div>
  36. </body>
  37. </html>
  38. 复制代码

正方形

使用 css 实现一个宽高自适应的正方形

查看代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style>
  7. /* 都是像对于屏幕宽度的比例 */
  8. .square1 {
  9. width: 10%;
  10. height: 10vw;
  11. background: red;
  12. }
  13. /* margin/padding 百分比是相对父元素 width 的 */
  14. .square2 {
  15. width: 20%;
  16. height: 0;
  17. padding-top: 20%;
  18. background: orange;
  19. }
  20. /* 通过子元素 margin */
  21. .square3 {
  22. width: 30%;
  23. overflow: hidden; /* 触发 BFC */
  24. background: yellow;
  25. }
  26. .square3::after {
  27. content: '';
  28. display: block;
  29. margin-top: 100%; /* 高度相对于 square3 的 width */
  30. }
  31. </style>
  32. </head>
  33. <!-- 画一个正方形 -->
  34. <body>
  35. <div class="square1"></div>
  36. <div class="square2"></div>
  37. <div class="square3"></div>
  38. </body>
  39. </html>
  40. 复制代码

扇形

实现一个 1/4 圆、任意弧度的扇形

有多种实现方法,这里选几种简单方法(我看得懂的)实现。
查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. /* 通过 border 和 border-radius 实现 1/4 圆 */
  10. .sector1 {
  11. height: 0;
  12. width: 0;
  13. border: 100px solid;
  14. border-radius: 50%;
  15. border-color: turquoise tomato tan thistle;
  16. }
  17. /* 类似三角形的做法加上父元素 overflow: hidden; 也可以实现任意弧度圆 */
  18. .sector2 {
  19. height: 100px;
  20. width: 200px;
  21. border-radius: 100px 100px 0 0;
  22. overflow: hidden;
  23. }
  24. .sector2::after {
  25. content: '';
  26. display: block;
  27. height: 0;
  28. width: 0;
  29. border-style: solid;
  30. border-width: 100px 58px 0;
  31. border-color: tomato transparent;
  32. transform: translate(42px,0);
  33. }
  34. /* 通过子元素 rotateZ 和父元素 overflow: hidden 实现任意弧度扇形(此处是60°) */
  35. .sector3 {
  36. height: 100px;
  37. width: 100px;
  38. border-top-right-radius: 100px;
  39. overflow: hidden;
  40. /* background: gold; */
  41. }
  42. .sector3::after {
  43. content: '';
  44. display: block;
  45. height: 100px;
  46. width: 100px;
  47. background: tomato;
  48. transform: rotateZ(-30deg);
  49. transform-origin: left bottom;
  50. }
  51. /* 通过 skewY 实现一个60°的扇形 */
  52. .sector4 {
  53. height: 100px;
  54. width: 100px;
  55. border-top-right-radius: 100px;
  56. overflow: hidden;
  57. }
  58. .sector4::after {
  59. content: '';
  60. display: block;
  61. height: 100px;
  62. width: 100px;
  63. background: tomato;
  64. transform: skewY(-30deg);
  65. transform-origin: left bottom;
  66. }
  67. /* 通过渐变设置60°扇形 */
  68. .sector5 {
  69. height: 200px;
  70. width: 200px;
  71. background: tomato;
  72. border-radius: 50%;
  73. background-image: linear-gradient(150deg, transparent 50%, #fff 50%),
  74. linear-gradient(90deg, #fff 50%, transparent 50%);
  75. }
  76. </style>
  77. </head>
  78. <body>
  79. <div style="display: flex; justify-content: space-around;">
  80. <div class="sector1"></div>
  81. <div class="sector2"></div>
  82. <div class="sector3"></div>
  83. <div class="sector4"></div>
  84. <div class="sector5"></div>
  85. </div>
  86. </body>
  87. </html>
  88. 复制代码

水平垂直居中

实现子元素的水平垂直居中

查看代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>水平垂直居中</title>
  5. <style type="text/css">
  6. .outer {
  7. height: 200px;
  8. width: 200px;
  9. background: tomato;
  10. margin: 10px;
  11. float: left;
  12. position: relative;
  13. }
  14. .inner {
  15. height: 100px;
  16. width: 100px;
  17. background: black;
  18. }
  19. /*
  20. * 通过 position 和 margin 居中
  21. * 缺点:需要知道 inner 的长宽
  22. */
  23. .inner1 {
  24. position: absolute;
  25. top: 50%;
  26. left: 50%;
  27. margin-top: -50px;
  28. margin-left: -50px;
  29. }
  30. /*
  31. * 通过 position 和 margin 居中 (2
  32. */
  33. .inner2 {
  34. position: absolute;
  35. top: 0;
  36. right: 0;
  37. bottom: 0;
  38. left: 0;
  39. margin: auto;
  40. }
  41. /*
  42. * 通过 flex 进行居中
  43. */
  44. .outer3 {
  45. display: flex;
  46. justify-content: center;
  47. align-items: center;
  48. }
  49. /**
  50. * 通过 position 和 transform 居中
  51. */
  52. .inner4 {
  53. top: 50%;
  54. left: 50%;
  55. transform: translate(-50%,-50%);
  56. position: absolute;
  57. }
  58. </style>
  59. </head>
  60. <body>
  61. <div class="outer outer1">
  62. <div class="inner inner1"></div>
  63. </div>
  64. <div class="outer outer2">
  65. <div class="inner inner2"></div>
  66. </div>
  67. <div class="outer outer3">
  68. <div class="inner inner3"></div>
  69. </div>
  70. <div class="outer outer4">
  71. <div class="inner inner4"></div>
  72. </div>
  73. </body>
  74. </html>
  75. 复制代码

清除浮动

要求:清除浮动

可以通过 clear:both 或 BFC 实现
查看代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>清除浮动</title>
  5. <style type="text/css">
  6. .outer {
  7. width: 200px;
  8. background: tomato;
  9. margin: 10px;
  10. position: relative;
  11. }
  12. .inner {
  13. height: 100px;
  14. width: 100px;
  15. background: pink;
  16. margin: 10px;
  17. float: left;
  18. }
  19. /* 伪元素 */
  20. .outer1::after {
  21. content: '';
  22. display: block;
  23. clear: both;
  24. }
  25. /* 创建 BFC */
  26. .outer2 {
  27. overflow: hidden;
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div class="outer outer1">
  33. <div class="inner"></div>
  34. </div>
  35. <div class="outer outer2">
  36. <div class="inner"></div>
  37. </div>
  38. </body>
  39. </html>
  40. 复制代码

弹出框

使用 CSS 写一个弹出框效果

查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. .bg {
  10. height: 666px;
  11. width: 100%;
  12. font-size: 60px;
  13. text-align: center;
  14. }
  15. .dialog {
  16. z-index: 999;
  17. position: fixed;
  18. top: 0;
  19. right: 0;
  20. bottom: 0;
  21. left: 0;
  22. background: rgba(0, 0, 0, 0.5);
  23. }
  24. .dialog .content {
  25. min-height: 300px;
  26. width: 600px;
  27. background: #fff;
  28. border-radius: 5px;
  29. border: 1px solid #ebeef5;
  30. box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  31. position: absolute;
  32. top: 50%;
  33. left: 50%;
  34. transform: translate(-50%, -50%);
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <div class="bg">
  40. 页面内容
  41. </div>
  42. <div class="dialog">
  43. <div class="content">
  44. 弹出框
  45. </div>
  46. </div>
  47. </body>
  48. </html>
  49. 复制代码

导航栏

要求:一个 div 内部放很多水平 div ,并可以横向滚动。

查看代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=div, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. body,html {
  10. margin: 0;
  11. padding: 0;
  12. }
  13. /* flex 实现 */
  14. /* .nav {
  15. display: flex;
  16. height: 30px;
  17. border: 1px solid #000;
  18. padding: 3px;
  19. overflow-x: auto;
  20. }
  21. .nav::-webkit-scrollbar {
  22. display: none;
  23. }
  24. .item {
  25. flex: 0 0 200px;
  26. height: 30px;
  27. margin-right: 5px;
  28. background: gray;
  29. } */
  30. /* inline-block 和 white-space: nowrap; 实现 */
  31. .nav {
  32. height: 30px;
  33. padding: 3px;
  34. border: 1px solid #000;
  35. overflow-x: auto;
  36. white-space: nowrap;
  37. }
  38. .nav::-webkit-scrollbar {
  39. display: none;
  40. }
  41. .item {
  42. display: inline-block;
  43. width: 200px;
  44. height: 30px;
  45. margin-right: 5px;
  46. background: gray;
  47. }
  48. </style>
  49. </head>
  50. <!-- 水平滚动导航栏 -->
  51. <body>
  52. <div class="nav">
  53. <div class="item">item1</div>
  54. <div class="item">item2</div>
  55. <div class="item">item3</div>
  56. <div class="item">item4</div>
  57. <div class="item">item5</div>
  58. <div class="item">item6</div>
  59. <div class="item">item7</div>
  60. <div class="item">item8</div>
  61. <div class="item">item9</div>
  62. </div>
  63. </body>
  64. </html>
  65. 复制代码

CSS 部分完,总结,Flex 无敌。

JavaScript 部分

手写 bind、call 和 apply

  1. Function.prototype.bind = function(context, ...bindArgs) {
  2. // func 为调用 bind 的原函数
  3. const func = this;
  4. context = context || window;
  5. if (typeof func !== 'function') {
  6. throw new TypeError('Bind must be called on a function');
  7. }
  8. // bind 返回一个绑定 this 的函数
  9. return function(...callArgs) {
  10. let args = bindArgs.concat(callArgs);
  11. if (this instanceof func) {
  12. // 意味着是通过 new 调用的 而 new 的优先级高于 bind
  13. return new func(...args);
  14. }
  15. return func.call(context, ...args);
  16. }
  17. }
  18. // 通过隐式绑定实现
  19. Function.prototype.call = function(context, ...args) {
  20. context = context || window;
  21. context.func = this;
  22. if (typeof context.func !== 'function') {
  23. throw new TypeError('call must be called on a function');
  24. }
  25. let res = context.func(...args);
  26. delete context.func;
  27. return res;
  28. }
  29. Function.prototype.apply = function(context, args) {
  30. context = context || window;
  31. context.func = this;
  32. if (typeof context.func !== 'function') {
  33. throw new TypeError('apply must be called on a function');
  34. }
  35. let res = context.func(...args);
  36. delete context.func;
  37. return res;
  38. }
  39. 复制代码

实现一个继承

  1. // 参考 You Dont Know JavaScript 上卷
  2. // 基类
  3. function Base() {
  4. }
  5. // 派生类
  6. function Derived() {
  7. Base.call(this);
  8. }
  9. // 将派生类的原型的原型链挂在基类的原型上
  10. Object.setPrototypeOf(Derived.prototype, Base.prototype);
  11. 复制代码

实现一个 new

  1. // 手动实现一个 new 关键字的功能的函数 _new(fun, args) --> new fun(args)
  2. function _new(fun, ...args) {
  3. if (typeof fun !== 'function') {
  4. return new Error('参数必须是一个函数');
  5. }
  6. let obj = Object.create(fun.prototype);
  7. let res = fun.call(obj, ...args);
  8. if (res !== null && (typeof res === 'object' || typeof res === 'string')) {
  9. return res;
  10. }
  11. return obj;
  12. }
  13. 复制代码

实现一个 instanceof

  1. // a instanceof b
  2. function _instanceof(a, b) {
  3. while (a) {
  4. if (a.__proto__ === b.prototype) return true;
  5. a = a.__proto__;
  6. }
  7. return false;
  8. }
  9. 复制代码

手写 jsonp 的实现

  1. // foo 函数将会被调用 传入后台返回的数据
  2. function foo(data) {
  3. console.log('通过jsonp获取后台数据:', data);
  4. document.getElementById('data').innerHTML = data;
  5. }
  6. /**
  7. * 通过手动创建一个 script 标签发送一个 get 请求
  8. * 并利用浏览器对 <script> 不进行跨域限制的特性绕过跨域问题
  9. */
  10. (function jsonp() {
  11. let head = document.getElementsByTagName('head')[0]; // 获取head元素 把js放里面
  12. let js = document.createElement('script');
  13. js.src = 'http://domain:port/testJSONP?a=1&b=2&callback=foo'; // 设置请求地址
  14. head.appendChild(js); // 这一步会发送请求
  15. })();
  16. // 后台代码
  17. // 因为是通过 script 标签调用的 后台返回的相当于一个 js 文件
  18. // 根据前端传入的 callback 的函数名直接调用该函数
  19. // 返回的是 'foo(3)'
  20. function testJSONP(callback, a, b) {
  21. return `${callback} + (${a + b})`;
  22. }
  23. 复制代码

ajax 的实现

感觉这个有点无聊了……
查看代码

  1. // Asynchronous Javascript And XML
  2. function ajax(options) {
  3. // 选项
  4. var method = options.method || 'GET',
  5. params = options.params,
  6. data = options.data,
  7. url = options.url + (params ? '?' + Object.keys(params).map(key => key + '=' + params[key]).join('&') : ''),
  8. async = options.async === false ? false : true,
  9. success = options.success,
  10. headers = options.headers;
  11. var request;
  12. if (window.XMLHttpRequest) {
  13. request = new XMLHttpRequest();
  14. } else {
  15. request = new ActiveXObject('Microsoft.XMLHTTP');
  16. }
  17. request.onstatechange = function() {
  18. /**
  19. readyState:
  20. 0: 请求未初始化
  21. 1: 服务器连接已建立
  22. 2: 请求已接收
  23. 3: 请求处理中
  24. 4: 请求已完成,且响应已就绪
  25. status: HTTP 状态码
  26. **/
  27. if (request.readyState === 4 && request.status === 200) {
  28. success && success(request.responseText);
  29. }
  30. }
  31. request.open(method, url, async);
  32. if (headers) {
  33. Object.keys(headers).forEach(key => request.setRequestHeader(key, headers[key]));
  34. }
  35. method === 'GET' ? request.send() : request.send(request.data);
  36. }
  37. // e.g.
  38. ajax({
  39. method: 'GET',
  40. url: '...',
  41. success: function(res) {
  42. console.log('success', res);
  43. },
  44. async: true,
  45. params: {
  46. p: 'test',
  47. t: 666
  48. },
  49. headers: {
  50. 'Content-Type': 'application/json'
  51. }
  52. })
  53. 复制代码

reduce 的实现

  1. function reduce(arr, callback, initial) {
  2. let i = 0;
  3. let acc = initial === undefined ? arr[i++] : initial;
  4. for (; i < arr.length; i++) {
  5. acc = callback(acc, arr[i], i, arr);
  6. }
  7. return acc;
  8. }
  9. 复制代码

实现 generator 的自动执行器

要求是 yield 后面只能是 Promise 或 Thunk 函数,详见 es6.ruanyifeng.com/#docs/gener…

  1. function run(gen) {
  2. let g = gen();
  3. function next(data) {
  4. let result = g.next(data);
  5. if (result.done) return result.value;
  6. if (result.value instanceof Promise) {
  7. result.value.then(data => next(data));
  8. } else {
  9. result.value(next);
  10. }
  11. }
  12. return next();
  13. }
  14. // ======== e.g. ==========
  15. function func(data, cb) {
  16. console.log(data);
  17. cb();
  18. }
  19. function *gen() {
  20. let a = yield Promise.resolve(1);
  21. console.log(a);
  22. let b = yield Promise.resolve(2);
  23. console.log(b);
  24. yield func.bind(null, a + b);
  25. }
  26. run(gen);
  27. /**
  28. output:
  29. 1
  30. 2
  31. 3
  32. **/
  33. 复制代码

节流

老生常谈了,感觉没必要写太复杂

/**
 * 节流函数 限制函数在指定时间段只能被调用一次
 * 用法 比如防止用户连续执行一个耗时操作 对操作按钮点击函数进行节流处理
 */
function throttle(func, wait) {
  let timer = null;
  return function(...args) {
    if (!timer) {
      func(...args);
      timer = setTimeout(() => {
        timer = null;
      }, wait);
    }
  }
}
复制代码

防抖

/**
 * 函数调用后不会被立即执行 之后连续 wait 时间段没有调用才会执行
 * 用法 如处理用户输入
 */
function debounce(func, wait) {
  let timer = null;

  return function(...args) {
    if (timer) clearTimeout(timer); // 如果在定时器未执行期间又被调用 该定时器将被清除 并重新等待 wait 秒
    timer = setTimeout(() => {
      func(...args);
    }, wait);
  }
}
复制代码

手写 Promise

简单实现,基本功能都有了。

const PENDING = 1;
const FULFILLED = 2;
const REJECTED = 3;
function MyPromise(executor) {
    let self = this;
    this.resolveQueue = [];
    this.rejectQueue = [];
    this.state = PENDING;
    this.val = undefined;
    function resolve(val) {
        if (self.state === PENDING) {
            setTimeout(() => {
                self.state = FULFILLED;
                self.val = val;
                self.resolveQueue.forEach(cb => cb(val));
            });
        }
    }
    function reject(err) {
        if (self.state === PENDING) {
            setTimeout(() => {
                self.state = REJECTED;
                self.val = err;
                self.rejectQueue.forEach(cb => cb(err));
            });
        }
    }
    try {
        // 回调是异步执行 函数是同步执行
        executor(resolve, reject);
    } catch(err) {
        reject(err);
    }
}
MyPromise.prototype.then = function(onResolve, onReject) {
    let self = this;
    // 不传值的话默认是一个返回原值的函数
    onResolve = typeof onResolve === 'function' ? onResolve : (v => v); 
    onReject = typeof onReject === 'function' ? onReject : (e => { throw e });
    if (self.state === FULFILLED) {
        return new MyPromise(function(resolve, reject) {
            setTimeout(() => {
                try {
                    let x = onResolve(self.val);
                    if (x instanceof MyPromise) {
                        x.then(resolve);
                    } else {
                        resolve(x);
                    }
                } catch(e) {
                    reject(e);
                }
            });
        });
    }
    if (self.state === REJECTED) {
        return new MyPromise(function(resolve, reject) {
            setTimeout(() => {
                try {
                    let x = onReject(self.val);
                    if (x instanceof MyPromise) {
                        x.then(resolve);
                    } else {
                        resolve(x);
                    }
                } catch(e) {
                    reject(e);
                }
            });
        });
    }

    if (self.state === PENDING) {
        return new MyPromise(function(resolve, reject) {
            self.resolveQueue.push((val) => {
                try {
                    let x = onResolve(val);
                    if (x instanceof MyPromise) {
                        x.then(resolve);
                    } else {
                        resolve(x);
                    }
                } catch(e) {
                    reject(e);
                }
            });
            self.rejectQueue.push((val) => {
                try {
                    let x = onReject(val);
                    if (x instanceof MyPromise) {
                        x.then(resolve);
                    } else {
                        resolve(x);
                    }
                } catch(e) {
                    reject(e);
                }
            });
        });
    }
}
MyPromise.prototype.catch = function(onReject) {
    return this.then(null, onReject);
}
MyPromise.all = function(promises) {
    return new MyPromise(function(resolve, reject) {
        let cnt = 0;
        let result = [];
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(res => {
                result[i] = res;
                if (++cnt === promises.length) resolve(result);
            }, err => {
                reject(err);
            })
        }
    });
}
MyPromise.race = function(promises) {
    return new MyPromise(function(resolve, reject) {
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(resolve, reject);
        }
    });
}
MyPromise.resolve = function(val) {
    return new MyPromise(function(resolve, reject) {
        resolve(val);
    });
}
MyPromise.reject = function(err) {
    return new MyPromise(function(resolve, reject) {
        reject(err);
    })
}
复制代码

实现一个路由 - Hash

实现原理就是监听 url 的哈希值变化了

<!DOCTYPE html>
<html>
<head>
  <title>hash 路由</title>
</head>
<body>
  <header>
    <a href="#home">首页</a>
    <a href="#center">个人中心页</a>
    <a href="#help">帮助页</a>
  </header>
  <section id="content"></section>
  <script>
    window.addEventListener('hashchange', (e) => {
      let content = document.getElementById('content');
      content.innerText = location.hash;
    })
  </script>
</body>
</html>
复制代码

路由实现 - history

<!DOCTYPE html>
<html>
<head>
  <title>history 路由</title>
</head>
<body>
  <header>
    <a onclick="changeRoute(this)" data-path="home">首页</a>
    <a onclick="changeRoute(this)" data-path="center">个人中心页</a>
    <a onclick="changeRoute(this)" data-path="help">帮助页</a>
  </header>
  <section id="content"></section>
  <script>
    function changeRoute(route) {
      let path = route.dataset.path;
      /**
       * window.history.pushState(state, title, url)
       * state:一个与添加的记录相关联的状态对象,主要用于popstate事件。该事件触发时,该对象会传入回调函数。
       *        也就是说,浏览器会将这个对象序列化以后保留在本地,重新载入这个页面的时候,可以拿到这个对象。
       *        如果不需要这个对象,此处可以填 null。
       * title:新页面的标题。但是,现在所有浏览器都忽视这个参数,所以这里可以填空字符串。
       * url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。
       */
      changePage(path);
      history.pushState({ content: path }, null, path);
    }
    /**
     * 调用 history.pushState() 或者 history.replaceState() 不会触发 popstate 事件。
     * 点击后退、前进按钮、或者在 js 中调用 history.back()、history.forward()、history.go() 方法会触发
     */ 
    window.addEventListener('popstate', (e) => {
      let content = e.state && e.state.content;
      changePage(content);
    });
    function changePage(pageContent) {
      let content = document.getElementById('content');
      content.innerText = pageContent;
    }
  </script>
</body>
</html>

作者:我不吃饼干呀
链接:https://juejin.im/post/5c9edb066fb9a05e267026dc
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。