web前端之JavaScript权威指南(JavaScript语言核心)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript语言核心</title>
<script type="text/javascript">
//所有双斜线之后的内容都是注释
//变量是通过var关键字进行申明的
var x;//声明一个变量
//变量值可以通过等号进行赋值
x=0;//现在变量的值就变为0了
//JavaScript支持多种变量的值
x=1;//数字
x=0.01;//整数和实数共用一种类型
x="hello word";//双引号之间构成字符串
x='hello word';//单引号之间构成字符串
x=true;//布尔值
x=null;//null是一个特殊字符,表示"空"
x=undefined;//undefined和null类似
//javascript的对象
var book={//对象
topic:"JavaScript",//属性
fat:"true",
}
book.topic //==>JavaScript
book[fat] //==>true
//通过[]和.对属性进行访问
book.author="fzw";//通过赋值获得一个新的属性
book.contents={};//{}是一个空对象,它没有属性
//JavaScript同样支持数组(以数字为索引的列表)
var primes=[2,3,5,7,9];
primes[0];//==>2
primes.length;//==>数组长度
primes[primes.length-1];//==>9最后一个值
primes[5]=9;//添加一个新的值
primes[5]=11;//改变一个值
var empty=[];//[]空值,具有0个元素
//数组和对象可以相互嵌套存在
var points=[
{x:0,y:0},
{x:1,y:1}
];
var data={
trial1=[[1,2],[3,4]];
trial2=[[2,3],[4,5]];
};
//JavaScript常见算法
3+2 //==>5
3-2 //1
3*3 //9
3/3 //1
points[1].x-points[0].x //复杂的操作数也能完成
'3'+'2' //32 字符串连接
var count = 0;
count++;//自增1
count--;//自减1
count +=2;//自增2
count;//2
var x=2;
var y=3;
x==y;//false 判断是否相等
x != y;//true 判断是否不等
x<y;//
x>y;//
"two">"three";//true tw在字母表中索引大于th
false==(x>y);//true false等于false
//逻辑运算符是对布尔值的合并或求反
(x==2) && (y==3);//true 两个比较都是true,&&表示"与"
(x>3)||(y<3);//false 两个都是false,||表示"或"
!(x == y);//true "!"表示求反
function plus1(x){//定义一个plus1的函数,带有参数x
return x+1;
}
plus1(3);//传出4
var square=function(x){ //函数也是一种值,可以赋值给变量
return x*x;//计算函数的值
};//分号标识了赋值语句的结束
square(plus1(3));//==>16在一个变量中调用两次函数
// 当将函数和对象写在一起时,我们称为方法;
var a=[];//创建一个空数组
a.push(1,2,3);//push()方法向数组中添加元素
a.reverse();//将数组元素次序反转
//我们也可以定义自己的方法,"this"关键字是对定义方法对象的引用:这里的例子上上下文中提到的包含两个点位置信息的数组
points.dist=function(){//定义一个方法用来计算两点之间的距离
var p1=this[0];//调用数组前两个元素
var p2=this[1];//
var a = p2.x-p1.x;//x坐标上的距离
var b=p2.y-p1.y;//y坐标上的距离
return Math.sqrt(a*a+b*b);//用Math.sqrt()来计算平方根
}
points.dist();//==>求两点之间的距离
//这些JavaScript语句使用该语法包含的条件判断和循环
//使用了类似java,c,c++类似的语法
function abs(x){//求绝对值的函数
if(x>=0){
return x;
}
else{
return -x;
}
}
abs(-5);
function factorial(n){//计算阶乘
var product=1;
while(n>1){
product *= n;
n--;
}
return product;
}
factorial(4)
function factorial2(n){
var i, product=1;
for(i=2;i<=n;i++){
product *= i;
}
return product;
}
factorial2(5);
//定义一个构造函数以初始化一个新的point对象
function Point(x,y){ //按照惯例,构造方法均以大写字母开始
this.x=x; //关键字"this"指代初始化的实例
this.y=y; //将函数参数存储为对象的属性,不需要返回return
}
//使用new关键字和构造函数来创建一个实例
var p=new Point(1,1);//平面几何中的点(1,1)
//通过构造函数的prototye对象函数
//来给Point对象定义方法
Point.prototye.r=function(){
return Math.sqrt(this.x*this.x+this.y*this.y);//this指代调用这个方法的对象
}
//Point的实例对象p(以及所有的Point实例对象) 继承了方法r()
p.r(); //==>1.414
</script>
</head>
<body>
</body>
</html>