/*历遍对象*/
var obj1 = {
a1: 1,
a2: 'string',
a3: 2,
a4: 3
};
for(var p in obj1){
console.log(p);//输出属性名称
console.log(obj1[p]);//输出属性的值
}
console.log('--------------------------------');
/*将所有对象属性复制至一个数组中*/
var o = {x:1, y:2, z:3};
var a = [],i = 0;
for(a[i++] in o)/*empty*/;
for(var b in a){
console.log(b);//输出数组索引
console.log(a[b]);//输出数组中存储的o对象的属性
console.log(o[a[b]]);//输出o对象的属性值
}
console.log('--------------------------------');
/*标签语句*/
var index = 3;
mainloop:while(index >= 0){
index--;
if(index >= 2)
continue mainloop;//结束本次循环
console.log(index);
}
console.log('--------------------------------');
index = 3;
breakloop:{
console.log(index);
while(index >= 0){
if(index <= 2){
//break;//结束while循环
break breakloop;//结束当前循环,跳到标签所指语句块的结束处
}
index--;
console.log(index);
}
console.log('结束while循环')
}
console.log('跳到标签语句块的结束');
console.log('--------------------------------');
/*return语句*/
function func1(){
var v1 = 10;
return v1;//结束函数,不再执行后面的语句
v1--;
console.log(v1);
}
var v2 = func1();
console.log(v2);
/*throw语句*/
var v3 = 3;
if(v3 < 2){
throw new Error("拋出错误,v3 < 2");
}
console.log('--------------------------------');
/*try...catch...finally*/
function func2(n){
if(n < 0){
throw new Error("n不能是负数!");
}
for(var i = 1; n > 1; i *= n, n--)/*empty*/;
return i;
}
try{//当try块内某处发生了异常时,调用catch块内的代码
var n = Number(prompt("请输入一个正整数",""));
var f = func2(n);
console.log(n + "! = " + f);
}catch(e){
console.log(e);
}finally{//不管try块中是否产生异常,finally块内的代码都会执行
//通常用于清理工作
console.log("总是执行finally块中的代码!");
}
console.log('--------------------------------');
/*严格模式*/
var hasStrictMode = (function(){
"use strict";
return (this === undefined);
})();
if(hasStrictMode == true){
console.log("当前浏览器支持严格模式!");
}else{
console.log("当前浏览器不支持严格模式!");
}
在谷歌浏览器中的输出: