Learning Javascript 3

with "Visual QuickStart Guide javascript and Ajax for the Web, Sixth Edition"

Chapter 3. Language Essentials

Arrays
var newCars = new Array("Toyota", "Honda", "Nissan");
newCars[2] returns "Nissan"

Loop
     for (var i=0; i<24; i++) {
        var newNum = Math.floor(Math.random() * 75) + 1;

        document.getElementById("square"  + i).innerHTML = newNum;
     }

var newNum;
     do {
        newNum = colBasis + getNewNum() + 1;
     }
     while (usedNums[newNum]);
remember that the do block of code always gets executed, whether the while check evaluates to true or false.

switch/case
function saySomething() {
     switch(this.value) {
        case "Lincoln":
           alert("Four score and seven years ago…");
           break;
        case "Kennedy":
           alert("Ask not what your country can do for you…");
           break;
        case "Nixon":
           alert("I am not a crook!");
           break;
        default:
     }
}
we've done everything we want to do, and so we want to get out of the switch. In order to do that, we need to break out. Otherwise, we'll execute all of the code below, too.
The default section is where we end up if our switch value didn't match any of the case values. The default block is optional, but it's always good coding practice to include it, just in case (so to speak).

Detecting Objects
if (document.getElementById) {
 xxxxxxxxxxxxx
}
 else {
        alert("Sorry, your browser doesn't support this script");
}

browser detect
Apple's Safari browser claims that it is a Mozilla browser, even though it is not. And some browsers, such as Safari and Opera, allow you to set which browser you want it to report itself as.
The same goes for attempting to detect which version of javascript a browser supports. We strongly suggest that you do not use these detection methods, and use object detection instead.

try/throw/catch
function initAll() {
     var ans = prompt("Enter a number","");
     try {
        if (!ans || isNaN(ans) || ans<0) {
            throw new Error("Not a valid number");
        }
        alert("The square root of " + ans + " is " + Math.sqrt(ans));
     }
     catch (errMsg) {
        alert(errMsg.message);
     }
}

Once an error is thrown, javascript jumps out of the TRy block and looks for a corresponding catch statement. Everything between here and there is skipped over.
If no error was thrown, the code inside the catch will never be executed.

This's the end of my learning javascript program.

转载请注明: 转自船长日志, 本文链接地址: http://www.cslog.cn/Content/learn_javascript_3/

此条目发表在 站长文档 分类目录。将固定链接加入收藏夹。

发表评论