JS 定義一個全局變量 在局部變量中賦值 -- 得到局部變量中的值 測試


摘錄: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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM