JS 定义一个全局变量 在局部变量中赋值 -- 得到局部变量中的值 测试

时间:2021-02-21 10:29:49

摘录:https://bbs.csdn.net/topics/391110498?page=1

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>全局变量 局部变量</title>
</head>
<body>
    <script language="javascript">
        var number = -1; //文档加载结束以后才执行
 window.onload = function () { var height = 100; number = height; //重新赋值
 } alert(number); //第一个执行,所以number没变化 alert(-1);
        function a() { alert(number); //这里number就已经在onload函数里被重新赋值了 alert(100);
 } </script>
    <input type="button" value="a" onclick="a()" />
</body>

</html>

自己测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>全局变量 局部变量</title>
</head>
<body onload="w()">
    <button onclick="a()">anniu</button>
    <script>
        var num; alert(num); //第一个加载 alert(undefined)
        function w() { num = 100; alert(num); //第三个加载 alert(100);
 } alert("3" + num); //第二个加载 alert(3 undefined)
        function a() { alert("4" + num); //点击按钮后加载 alert(4 undefined)
 } </script>
</body>
</html>