Web开发技术梳理 0x3 JavaScript(0x0)类型、异常、Promise

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/88826121

猜数字游戏 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>猜数字游戏</title>
        <style>
            html {
                font-family: sans-serif
            }
            body {
                width: 50%;
                max-width: 800px;
                min-width: 480px;
                margin: 0 auto
            }
            .lastResult {
                color: white;
                padding: 3px
            }
        </style>
    </head>
    <body>
        <h1>猜数字游戏</h1>
        <p>我刚才随机选定了一个100以内的自然数。看你能否在 10 次以内猜中它。每次我都会告诉你所猜的结果是高了还是低了。</p>
        <div class="form">
            <label for="guessField">请猜数:</label>
            <input type="text" id="guessField" class="guessField">
            <input type="submit" value="确定" class="guessSubmit">
        </div>
        <div class="resultParas">
            <p class="guesses"></p>
            <p class="lastResult"></p>
            <p class="lowOrHi"></p>
        </div>
        <script>
            let randomNumber = Math.floor(Math.random()*100)+1;

            const guesses = document.querySelector('.guesses');
            const lastResult = document.querySelector('.lastResult');
            const lowOrHi = document.querySelector('.lowOrHi');
            const guessSubmit = document.querySelector('.guessSubmit');
            const guessField = document.querySelector('.guessField');

            let guessCount = 1;
            let resetButton;

            guessField.focus();

            function checkGuess(){
                const userGuess = Number(guessField.value);
                if(guessCount===1){
                    guesses.textContent = '上次猜的数:';
                }
                guesses.textContent += userGuess + ' ';

                if(userGuess===randomNumber){
                    lastResult.textContent = '恭喜你!猜对了!';
                    lastResult.style.backgroundColor = 'green';
                    lowOrHi.textContent = ' ';
                    setGameOver();
                }else if(guessCount===10){
                    lastResult.textContent = '!!!Game Over!!!';
                    lowOrHi.textContent = '';
                    setGameOver();
                }else{
                    lastResult.textContent = '猜错了!';
                    lastResult.style.backgroundColor = 'red';
                    if(userGuess<randomNumber){
                        lowOrHi.textContent = '你猜低了!';
                    }else if(userGuess>randomNumber){
                        lowOrHi.textContent = '你猜高了';
                    }
                }
                guessCount++;
                guessField.value = '';
                guessField.focus();
            }

            guessSubmit.addEventListener('click',checkGuess);

            function setGameOver(){
                guessField.disabled = true;
                guessSubmit.disabled = true;
                resetButton = document.createElement('button');
                resetButton.textContent = '开始新游戏';
                document.body.appendChild(resetButton);
                resetButton.addEventListener('click',resetGame);
            }
            function resetGame(){
                guessCount = 1;
                const resetParas = document.querySelectorAll('.resultParas p');
                for(let i=0;i<resetParas.length;i++){
                    resetParas[i].textContent = '';
                }
                resetButton.parentNode.removeChild(resetButton);

                guessField.disabled = false;
                guessSubmit.disabled = false;
                guessField.value = '';
                guessField.focus();

                lastResult.style.backgroundColor = 'white';

                randomNumber = Math.floor(Math.random()*100)+1;
            }
        </script>
    </body>
</html>

数据结构和类型

    基本数据类型:Boolean,null,undefined,Number,String,Symbol,Object。

字面量 (Literals)

    字面量是脚本中按字面意思给出的固定的值,而不是变量。

False等效值

    false,undefined,null,0,NaN,""

异常处理语句

    throw

//throw expression;
throw "Error2";   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };

    try...catch

    try...catch 语句标记一块待尝试的语句,并规定一个以上的响应应该有一个异常被抛出。如果我们抛出一个异常,try...catch语句就捕获它。

function getMonthName(mo) {
  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
  var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul",
                "Aug","Sep","Oct","Nov","Dec"];
  if (months[mo]) {
    return months[mo];
  } else {
    throw "InvalidMonthNo"; //throw keyword is used here
  }
}

try { // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
}
catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler -> your own function
}

    finally

openMyFile();
try {
    writeMyFile(theData); //This may throw a error
}catch(e){
    handleError(e); // If we got a error we handle it
}finally {
    closeMyFile(); // always close the resource
}

Promise

    Promise对象的状态:

  • pending:初始状态,即正在执行,不处于fulfilled或rejected
  • fulfilled:成功完成了操作
  • rejected:失败,没有完成操作。
  • settled:Promise处于fulfilled或rejected中的一个状态,不会是pending

 

    通过 XHR 加载图片

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Promise example</title>

    <link rel="stylesheet" href="">
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
    <h1>Promise example</h1>

    <p>Darth Vader image by <a href="https://www.flickr.com/photos/digital_stability/">Shawn Taylor</a>, published under a <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs 2.0 Generic</a> license.</p>
  </body>

  <script>
  function imgLoad(url) {
    // Create new promise with the Promise() constructor;
    // This has as its argument a function
    // with two parameters, resolve and reject
    return new Promise(function(resolve, reject) {
      // Standard XHR to load an image
      var request = new XMLHttpRequest();
      request.open('GET', url);
      request.responseType = 'blob';
      // When the request loads, check whether it was successful
      request.onload = function() {
        if (request.status === 200) {
        // If successful, resolve the promise by passing back the request response
          resolve(request.response);
        } else {
        // If it fails, reject the promise with a error message
          reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
        }
      };
      request.onerror = function() {
      // Also deal with the case when the entire request fails to begin with
      // This is probably a network error, so reject the promise with an appropriate message
          reject(Error('There was a network error.'));
      };
      // Send the request
      request.send();
    });
  }
  // Get a reference to the body element, and create a new image object
  var body = document.querySelector('body');
  var myImage = new Image();
  // Call the function with the URL we want to load, but then chain the
  // promise then() method on to the end of it. This contains two callbacks
  imgLoad('myLittleVader.jpg').then(function(response) {
    // The first runs when the promise resolves, with the request.response
    // specified within the resolve() method.
    var imageURL = window.URL.createObjectURL(response);
    myImage.src = imageURL;
    body.appendChild(myImage);
    // The second runs when the promise
    // is rejected, and logs the Error specified with the reject() method.
  }, function(Error) {
    console.log(Error);
  });
  </script>
</html>

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/88826121