代码改变世界

JS 变量

2018-07-02 09:54  钱先生  阅读(248)  评论(0编辑  收藏  举报

注: 以下来自 <<HeadFirst JavaScript 程序设计>> 人民邮电出处社, 袁国忠译

变量注意事项:

  • 如果在函数体没有用var声明变量, 这个变量会被当作是全局变量.
    • function playTrun(player, location) {
          points = 0;  //使用未声明的变量, 它会被自动视为全局变量
          if (location == 1){
              points = points + 100;
          }
         return points  
      }
      函数体未声明变量
  • 如果局部变量与全局变量同名, 全局变量会被遮住.
    • var beanCounter = 10;
      
      function getNumberOfItems(ordertype) {
          var beanCounter = 0;
          if (ordertype == "order" {
          console.log("ordertype: " + ordertype);
          }
          return beanCounter;  //在函数中每次使用的都是局部变量beanCounter. 全局变量和局部变量不会互相影响, 修改一个不会影响到另一个.
      }
      局部变量与全局变量同名

 

 

例: 取出数组中最大值和所有最大值的索引.

function sort(){
    var scores = [60,50,60,58,54,54,58,50,52,54,48,69,34,55,51,52,44,51,69,64,66,55,52,61,46,31,57,52,44,18,41,53,55,61,51,44];
    var element = scores[0];
    for (let index = 0; index < scores.length; index++) {
        var temp = scores[index];
        // console.log(scores[index+1])
        if (temp > element){
            element = temp;
        } else {
            continue;
        }
    }
    console.log(element)
    var i = [];
    for (let index = 0; index < scores.length; index++) {
        if (scores[index] == element){
            i.push(index);
        }
    }
    i.forEach(element => {
        console.log(element)
    });
}


sort()
取数组最大值及其索引

 

对象中调用函数

var fiat = {
    drive: function(){
        if (this.started){
            if (this.fuel > 0){
                alert (this.make + " " + this.model + "goes zoom zoom!");
            this.fuel = this.fuel-1;
            } else {
                alert("Uh oh, out of fuel");
                this.stop();
            }
        } else {
            alert("You need to start the engine first.")
        }
    },

    addFuel: function(amount){
        this.fuel = this.fuel + amount;
    }
}


fiat.drive()
对象中调用函数(匿名函数)

 

读取网页内容

1. 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>Document</title>
</head>
<body>
    <h1>Dog Bark!</h1>
    <p id="code1">The eagle is in the</p>
    <p id="code2">The fox is in the</p>
    <p id="code3">snuck into the garden last night</p>
    <p id="code4">They said it would rain</p>
    <p id="code5">Does the red robin crow at</p>
    <script src = "test001.js">
    </script>
</body>
</html>
HTML

2. JS脚本

var access = document.getElementById("code3");

var code = access.innerHTML;

code = code + "midnight";

alert(code);
JS

 

 

回调函数(事件处理程序 event handler) callback:

1. 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>Document</title>
    <style>.redtext{color: red}</style>  <!-- 设置属性redtext值颜色为红色-->
</head>
<body>

    <script src = "test001.js">
    </script>
    <h1>Dog Bark!</h1>
    <p id="code1">The eagle is in the</p>
    <p id="code2">The fox is in the</p>
    <p id="code3">snuck into the garden last night</p>
    <p id="code4">They said it would rain</p>
    <p id="code5">Does the red robin crow at</p>

</body>
</html>
HTML

2. JS

function init() {
    var abc = document.getElementById("code1");
    abc.innerHTML = "I am Satan";

    abc.setAttribute("class", "redtext");  //定义属性redtext, 以便在网页中为该属性值设置颜色.
}

window.onload = init;  //确保网页加载完成之后, 会执行回调函数. 这样无论<script>标签是放在body其它代码前面还是后面, script标签里的内容都能够被执行.
JS