第一篇 JS 语言基础之自增自减

124 阅读1分钟

1. script 的位置

放在头部前面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        let box = document.getElementById('box');
        console.log(box); // => null 还没读到结构 
        box.style.color = 'red' ; //=> 报错
    </script>
</head>
<body>
   <div id="box"> 我的颜色变成红色了吗?</div>
</body>
</html>

image.png

因为 JS 要操作元素结构 , 所以放在 body 末尾,保证页面结构加载完成才去做 script 里面的事情

- 如果放在 html 外面,浏览器也会把 script 解析到 html 里面.

注意事项:

如果放到头部,可能导致无法获取到想要操作的元素

改进:

如果一定要放在头部 ,引入 window.onload 事件

当页面中的结构和内容都加载完成才执行该事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        window.onload = function(){
            let box = document.getElementById('box');
        console.log(box); 
        box.style.color = 'red' ; 
        }
    </script>
</head>
<body>
   <div id="box"> 我的颜色变成红色了吗?</div>
</body>
</html>

JQ 中也有一个应对的方法${document}.ready(function(){})

但是仍旧有区别

以及外链 同步异步 等等

未完待续...

2. i++ 与 ++i 自增与自减

  1. i++ ++i i-- --i 都是纯粹的数学运算
        let i = '10';
        
        i = i + 1 => '10' + 1 => '101'
        i += 1 => '101'
        i++ => i => 11
  1. i++ 和++i 都是数学运算中的累加 1,i 都会增加 1.

新 i = 旧 i + 1

区别是计算的顺序

i++ 先参与运算 然后再自增 1

i++ 的值等于 旧 i .新 i = 旧 i + 1

++i 先累加然后再参与运算

++i 的值等于新 i.

练一练

        let i = 3;
        let m = 5+(++i)+(i++)+3-2+(--i)+(i--)-2 ;
       console.log(i); //3
       console.log(m); //20

image.png