请原谅一个js初学者不可避免的把js和java相提并论,并兴奋地发现js很灵活很有动感啊
1.switch可用于字符串:
var a = 'abc'; switch(a){ case 1: alert("number");break; case true:alert('boolean');break; case 'abc': alert('String');break; }
with(document){ writeln('hello'); writeln('world'); }//这样就不用每次都写document.writeln(...)
3.foreach语句:
function Person(name ,gender){ this.name = name; this.gender = gender; this.shout = function (){return 'shut up !';} } var p = new Person('macondo','male'); for(var i in p){ document.writeln(i+' = '+p[i]+'<br>'); }这里foreach语句比java中得更进一步,原因是p.name也可以写成p['name']
var fruit = new Array(); fruit.push('apple');//等同于fruit[0] = 'apple' fruit.push('pear');//等同于fruit[1] = 'pear' //等同于var fruit = new Array('apple','pear'); //等同于var fruit = ['apple','pear']; fruit['a']='orange';//我觉得就像fruit.a='orange',其实它不再数组里,而是fruit的一个属性 //fruit.a='orange'; for (var i in fruit){ document.writeln(i+' = '+fruit[i]+'<br>'); } var t = fruit.length;//这里必须先把length赋给t for(var i=0;i<t;i++){//若再for循环里用length, pop()一下length就被改变了 document.writeln('pop:'+fruit.pop()+'<br>'); } document.writeln(fruit['a']);//下目标为‘a'的元素没被删除,且不会被pop掉
5.js中的数据类型有:string,boolean,number,undefined,function(函数也是对象),其他的都是object类型,可以同typeof运算符得到数据类型
function add(a,b){return a+b;} with(document){ writeln(typeof e);//undefined writeln(typeof 4.5);//number writeln(typeof (1/0));//number writeln(typeof true);//boolean writeln(typeof '');//string writeln(typeof add);//function writeln(typeof new add());//object writeln(typeof null)//也是object? writeln('<br>'); writeln(typeof new Boolean('abc'));//objcet,因为boolean也是继承自object writeln(typeof Boolean('abc'));//boolean,这里是强制类型转换,把'abc'变成true writeln(typeof new String('abc'));//同上 writeln(typeof String(true)); }
不知为什么null竟然也是object,我的理解是除了原始数据类型(number,boolean,string等)之外,其他的包括(Boolean,String)都是object继承来的。Boolean和boolean是有一点区别的
6.函数可以先使用,后声明
7.除了在函数里面声明的变量是local variable之外,在for,if等{}块中声明的变量是全局变量
8.js numbers are 64-bit floating point numbers (ex. var a=444;)
9.字符串可用<、>比较大小