《DOM Scripting》学习笔记-——第二章 js语法

2023-07-29,,

《Dom Scripting》学习笔记

第二章 Javascript语法

本章内容:

1、语句。

2、变量和数组。

3、运算符。

4、条件语句和循环语句。

5、函数和对象。

语句(statements

注释(comments

方法:

1、// Note to self: comments are good.

2、/* Note to self:
comments are good */

3、<!— This is
a comment in JavaScript.

(In HTML, you would need to close the comment with —>:
<!— This is a comment in HTML —>)

变量(variables

声明(declare)变量:

1、 
var mood;
       var age;

2、 
var mood, age;

声明变量并赋值(assignment):

1、 
var mood =
"happy";
       var age = 33;

2、  var mood = "happy", age = 33;(最有效的方法)

3、 
var mood, age;
       mood = "happy";
       age = 33

变量的数据类型(Data types

一、字符串(strings

格式:用单引号或双引号包含字符串内容。

var mood = 'happy';
var mood = "happy";

防止字符串逃逸(escaping)的方法:

var mood = 'don\'t ask';

var height = "about 5'10\" tall";

二、数值(numbers


三、布尔值

取值:true或false

区分字符串“true”与布尔值true:

This
will set the variable married to the Boolean value true:
var married = true;
In this case, married is a string containing the word “true”:
var married =“true”

四、数组

由名字相同的多个值构成的一个集合,集合中每个值都是数组的元素。

一、声明、填充数组的方法:

1、

var beatles = Array(4);
beatles[0] = "John";
beatles[1] = "Paul";
beatles[2] = "George";
beatles[3] = "Ringo";

2、

var beatles =
Array("John","Paul","George","Ringo");

3、

var beatles =
["John","Paul","George","Ringo"];

二、数组的元素种类

字符串、数值、布尔值、变量、数组

var lennon = Array("John",1940,false);
var beatles = Array();
beatles[0] = lennon;

三、关联数组

元素下标不是整数数字,是字符串。可以提高脚本可读性。

var beatles = Array();
beatles["vocalist"] = lennon

操作

算数运算符

+

将数值和字符串相加会得到字符串

alert ("10" + 20);//1020
alert (10 + 20);//30

条件语句

 if (condition) {
     statements;
     }

条件的求值结果永远是一个布尔值,花括号中的语句,只有在给定条件的求职结果是true时才会得到执行。

比较操作符:===、!=

逻辑操作符:&&(与)、||(或)、!(非)

循环语句

While

while (condition) {
statements;
}

do…while

 do {
statements;
} while (condition);

for

for (initial condition; test condition; alter condition) {
statements;
}

等同于

initialize;
while (condition) {
statements;
increment;
}

函数

定义函数

function name(arguments) {
statements;
}

函数返回值:数值、字符串、数组、布尔值

变量作用域(scope

 全局变量(global variable

 局部变量(local variable

 如果在某个函数中使用了var,那个变量就是一个局部变量,它将只存在于这个函数的上下文中;若没有使用var,那么就是一个全局变量。如果脚本中存在一个与之同名的变量,这个函数将覆盖那个现有的值。

function square(num) {
total = num * num;
return total;
}
var total = 50;
var number = square(20);
alert(total);

//弹出400

function square(num) {
var total = num * num;
return total;
}
var total = 50;
var number = square(20);
alert(total);

//弹出50

 

对象(objects

对象是自我包含的数据集合,包含在对象里的数据可以通过属性和方法两种方式访问。

属性(properties):是隶属于某个特定对象的变量。

方法(methods):是只有某个特定对象才能调用的函数。

用户定义对象(user-defined
objects
)。

内建对象(native objects)。

宿主对象(host objects):js中一些已经预先定义好的对象,不是由js语言本身而是由它的运行环境提供的,就是各种web浏览器。由web浏览器提供的预定义对象成为宿主对象。

整理的思维导图:

《DOM Scripting》学习笔记-——第二章 js语法的相关教程结束。

《《DOM Scripting》学习笔记-——第二章 js语法.doc》

下载本文的Word格式文档,以方便收藏与打印。