index.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>箭头函数应用场景</title>
  8. </head>
  9. <body>
  10. <div style="width:200px;height:200px;background:green;" id="box"></div>
  11. <script>
  12. // 点击div 2s后变颜色
  13. let ad = document.getElementById("box");
  14. ad.addEventListener('click',function(){
  15. let that = this
  16. setTimeout(function(){
  17. //this指window
  18. that.style.background = 'pink'
  19. },2000)
  20. //箭头
  21. setTimeout(()=>{
  22. this.style.background = 'pink'
  23. })
  24. })
  25. //从数组中返回偶数元素
  26. const arr = [1,2,4,5,3,344]
  27. const result = arr.filter(function(item){
  28. if(item % 2 === 0){
  29. return true;
  30. }else{
  31. return false;
  32. }
  33. })
  34. //箭头
  35. const result = arr.filter(item=>item%2 === 0)
  36. //箭头函数适合与this无关的回调,定时器,数组的方法回调
  37. //不适合与this有关的回调,不适合事件回调,对象的方法
  38. </script>
  39. </body>
  40. </html>