JavaScript 基础笔记
JavaScript 是一种脚本语言,通常由各种浏览器解释和执行。 JavaScript 是由浏览器执行的语句序列。JavaScript 语句序列是浏览器执行的指令,这个指令的目标是告诉浏览器去做什么。(JavaScript is a sequence of statements to be executed by the browser. A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.) 如它可以对页面元素进行一些操作:验证表单,增删改查一些 HTML 文档中的元素,处理各种事件——如鼠标事件等等,还可以操作页面的各种控件,如 ActiveX, Applet, Flash 等等。
它的正式名称是 EMACScript,正式的标准是 ECMA-262.
语法
变量
变量分为三类:
- 字串型
String
- 数字型
int, long, float, double
- 逻辑型
boolean
声明和定义变量。JavaScript 是弱类型语言,以 var 声明所有变量,在赋值时,类型得到确认。如:
- 声明并赋值一起。
var varName = xxx; // xxx 可以是任意类型。
- 先声明后赋值。
var a, b;
a = "张三";
b = 32.5;
如果是把文本赋值给一个变量,文本需要用双引号括起来(When you assign a text value to a variable, use quotes around the value).
如果一个变量申明了两次, 并且第一次就被赋值了, 如果第二次声明没有明确赋值, 它的值仍然是第一次赋的那个值. 如:
var x = 5;
var x;
以上两句执行后, x 的值还是5.
注:这里变量定义符号 var 和 Scala 是一致的。
switch-case 语句
在 JavaScript 中,case 可以接受的类型有是所有 JavaScript 支持的数据类型,包括但不限于 int, char 和字符串类型。
注:这点比 Java 要强大很多,Java 在 Java 7之前,case 关键字后只能跟 int, char, 枚举类型等(参这里),从 Java 7开始,才开始接受 String 类型的对象(参这里)。
假值
以下值会被视为 false:
- false
- null
- undefined
- ' ' //空字符串
- 0 // 数字0
- NaN
其他所有值都被视为 true, 包括 true, 字符串 "false" 以及其他所有的对象.
== 和 ===
在 JavaScript 中,== 定义为“is equal to”,判断值是否相等,类似于 Java 中的 Object.equals()
方法。用于表示两个对象全等,即类型和内容都相等,JavaScript 用了一个新符号 ===,它被定义为“ is exactly equal to (value and type)”。实验表明: 3=="3" 的值为 true, 而3==="3"的值为 false
和以上对应的不等号也有两个:!=
和 !==
注:
在 Java 中,两个对象的内容相等,则用 Object.equals 比较两个对象时,将返回 true. 而如果 o1 == o2 为 true 的话,则 o1 和 o2 为符合定义的“相等”的对象。
语句
按照 JavaScript 标准, 分号就代表一条语句结束了, 不过 JavaScript 并不强制使用分号,换行也表示一条语句的结束。但用分号明确标识语句结束有另外的好处: 能在一行写多条 JavaScript 语句, 必须用到这个特性的就是 for 循环.
JavaScript 固然是按顺序执行的, 但函数如果没有调用, 是不会自己执行的, 如整个 body 部分的代码如下, 输出的页面只是空白: 定义的函数如果不调用,是不会自动执行的.
<body>
<script type="text/javascript">
function hello() {
document.write("没有任何东西")
}
</script>
</body>
而如果是下面这样, 就会显示文字"".
<body>
<script type="text/javascript">
function hello() {
document.write("没有任何东西")
}
hello() //调用!
</script>
</body>
这个例子也体现出 Java 和 JavaScript 相同的语法:
1. JavaScript 语句块就是用大括号把多句括起来.
2. 注释就两种格式: // 和 /**/
注:有关 JavaScript 函数,参本站的"JavaScript 函数笔记"页面。
内置对象
JavaScript 内置了8个对象:Array, Boolean, Date, Function, Math, Number, String, RegExp, Global. 其中 Math 不需要建立对象就可以使用其函数。在维基百科上提到了 Date 和 Math 对象与 Java 的渊源:JavaScript's Math and Date objects are based on classes from Java 1.0.
Array
参本站的《JavaScript Array》页面。
Boolean
虽然这是个内置对象,但创建时,是这样的:var flag = true;
or var flag = false;
而不是:var flag = new Boolean(true);
Date
创建 Date 对象:var d = new Date();
它比较常用的函数就是:getTime, setTime, getYear, setYear, getMonth, ... 等等这类,可以在用 NetBeans 编辑脚本时查看代码提示。
这里值得一提的是 JavaScript 中日期值的范围:
- second, ninunte: [0, 59]
- hour: [0, 23]
- week: [0, 6]
- day in a month: [1, 31]
- month: [0, 11]
- year: [1900, +infinite)
Math
这个内置对象和其他的有些不一样,就是不需创建,直接使用它就行。所谓使用它,就是它的一些属性和函数,参下面在 NetBean 中的截图:
Function
这部分内容,参本站的: JavaScript 函数
Number
Number 对象是对原始数字类型的一个封装。
创建语法: var num = new Number(value);
//如果 value 不能转化为数字,则返回 NaN(Not-a-Number)
属性:
- constructor Returns the function that created the Number object's prototype
- MAX_VALUE Returns the largest number possible in JavaScript
- MIN_VALUE Returns the smallest number possible in JavaScript
- NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
- POSITIVE_INFINITY Represents infinity (returned on overflow)
- prototype Allows you to add properties and methods to an object
方法:
- toExponential(x) Converts a number into an exponential notation
- toFixed(x) Formats a number with x numbers of digits after the decimal point
- toPrecision(x) Formats a number to x length
- toString() Converts a Number object to a string
- valueOf() Returns the primitive value of a Number object
本小节的内容来源于:http://www.w3schools.com/jsref/jsref_obj_number.asp
String
String 对象用于操作一个有序的文本块。
创建对象的方法:
var txt = new String("string");
或:
var txt = "string";
属性:
- constructor Returns the function that created the String object's prototype
- length Returns the length of a string
- prototype Allows you to add properties and methods to an object
方法:
- charAt() Returns the character at the specified index,这里的 index 是从0开始的。
- charCodeAt() Returns the Unicode of the character at the specified index
- concat() Joins two or more strings, and returns a copy of the joined strings
- fromCharCode() Converts Unicode values to characters,它的 HELLO 字串是这么产生的:String.fromCharCode(72,69,76,76,79)
- indexOf() Returns the position of the first found occurrence of a specified value in a string
- lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
- match() Searches for a match between a regular expression and a string, and returns the matches
- replace() Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
- search() Searches for a match between a regular expression and a string, and returns the position of the match
- slice() Extracts a part of a string and returns a new string
- split() Splits a string into an array of substrings
- substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
- substring() Extracts the characters from a string, between two specified indices
- toLowerCase() Converts a string to lowercase letters
- toUpperCase() Converts a string to uppercase letters
- valueOf() Returns the primitive value of a String object
HTML 封装方法
- 一个字串的 HTML 封装方法返回一个带有 HTML 标签的字串,原先的字串包含在这对标签中。(The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.)
- anchor() Creates an anchor
- big() Displays a string using a big font
- blink() Displays a blinking string
- bold() Displays a string in bold
- fixed() Displays a string using a fixed-pitch font
- fontcolor() Displays a string using a specified color
- fontsize() Displays a string using a specified size
- italics() Displays a string in italic
- link() Displays a string as a hyperlink
- small() Displays a string using a small font
- strike() Displays a string with a strikethrough
- sub() Displays a string as subscript text
- sup() Displays a string as superscript text
来源:http://www.w3schools.com/jsref/jsref_obj_string.asp
Browser Objects Model(BOM)
几乎所有的浏览器都支持 JavaScript,这些浏览器会“内置”一些 JavaScript 对象,这个对象树形如右图(图的来源是bom tree)。
需要留意的几点:
- BOM 的实现,可能因为浏览器的不同而有差异——没有标准实现
- 顶层对象是 Window
- 除了 frames[],其余几个对象都是比较重要的
- document object 的内容很多,一般单独称为 DOM (Document Object Model) ,这是独立于浏览器的一个标准,这里仅仅是浏览器的一个实现而已。
这里是一个比较好的参考说明:http://www.dreamdu.com/javascript/what_is_browser_objects/
有关这些对象的属性、方法及示例总总,参考的介绍更方便一些,下面仅仅简单说明一下。
Window
window object 代表浏览器的一个打开的窗口,即当前窗口。如果文档中包含 frame,那么浏览器除了给当前打开的窗口创建一个 window object,还会给每个 frame 也创建一个额外的 window object。它的属性和方法非常多,需要专门的记录。
它有常用的三个消息框函数: alert, confirm, prompt
1. alert 直接弹出内容。在简单调试 Javascript 代码时常用到。
function hello(a, b, c){
alert(a);
alert(b);
alert(c);
}
hello(1);
对于这个函数,会先弹出1, 然后弹出显示的是 undefined
2. confirm 提示用户选择,如选“是”,则继续执行,若“否”,则终止执行。
3. prompt 弹出框并接受用户输入。这相当于全局函数,即 window 对象的函数。
其他。在 JavaScript 中定义的函数和变量,都是属于 window 对象的属性。
<script type="text/javascript">
var abc = "something";
function hello() {
alert("hello");
}
hello();
window.hello();
// 和上面一行的含义一样
alert(window.abc);
// 和 alert(abc) 一样
</script>
w3schools ref: http://www.w3schools.com/jsref/obj_window.asp
Navigator
navigator object 包含一些浏览器的信息,它的属性和方法都比较少:
属性:appCodeName, appName, appVersion, cookieEnabled, platform, userAgent
方法:
- javaEnabled()
- taintEnabled() 这个方法 Firefox 不支持。
w3schools ref: http://www.w3schools.com/jsref/obj_navigator.asp
Screen
screen object 包含访问者的显示屏幕的信息,只有属性,没有方法。属性也不多,干脆从 w3shools 上抄写过来:
- availHeight Returns the height of the screen (excluding the Windows Taskbar)
- availWidth Returns the width of the screen (excluding the Windows Taskbar)
- colorDepth Returns the bit depth of the color palette for displaying images,对这个属性的支持,很有意思,在我的机器上,当系统设置的深度设置为32位时,IE能支持到32位,而Firefox只有24位。
- height Returns the total height of the screen
- pixelDepth Returns the color resolution (in bits per pixel) of the screen
- width Returns the total width of the screen
w3schools ref: http://www.w3schools.com/jsref/obj_screen.asp
History
history object 包含了用户的访问历史。它的属性和方法也是非常少的:
属性:length
方法:back(), forward(), go(),注意最后一个方法使用时需要带参数。
w3schools ref: http://www.w3schools.com/jsref/obj_history.asp
Location
location object 包含当前 URL 的一些信息,详细内容都可以参看 w3schools 的链接,这里不再赘述,只是有一个很特殊的属性需要指出一下,location.hash 它表示的是当前链接的锚点值,而不是通常意义上的哈希,真是搞不懂怎么怎么用了这个名字的。
w3schools ref: http://www.w3schools.com/jsref/obj_location.asp
DOM
DOM 并不属于核心 JavaScript 核心部分,它分为 core DOM 和 HTML DOM 两部分,本站专门记录到《DOM 笔记》里。
HTML 中使用 JavaScript 片段的方式
代码具体书写的位置有好几种方式.
直接写在 HMTL 文档里
如果写在HTML文件内部, 它可以出现在<head>或<body>, 这有什么不同? 且看W3C教程中提到:
JavaScripts in the body section will be executed WHILE the page loads.
JavaScripts in the head section will be executed when CALLED.
写在独立的 *.js 文件里
以上是两种使用内部 JavaScript 的方式, 还有一种就是引用外部的 JavaScript 代码, 格式如下:
<script type="text/javascript" src="xxx.js"></script>
注意, 外部JavaScript文件中不能含有<script>标签
Eclipse
HMTL 元素的事件名称在哪里查询?Alt+/ 可以得到属性列表
参考资料
- W3CSchool: http://www.w3schools.com/js/default.asp(很系统的资料)
- ECMA-262: http://www.ecma-international.org/publications/standards/Ecma-262.htm