三、JavaScript 对象
JavaScript 中的所有事物都是对象:字符串、数值、数组、函数...
此外,JavaScript 允许自定义对象。对象只是带有属性和方法的特殊数据类型,和Java的很相似。
1.创建 JavaScript 对象(不好理解)
a.创建了对象的一个新实例,并向其添加了四个属性:
<script>
person=newObject();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";
document.write(person.firstname+ " is " + person.age + " years old.");
</script>
或者:person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
b. 使用函数来构造对象:
<script>
functionperson(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
boss=newperson("Bill","Gates",56,"blue");
document.write(boss.firstname+ " is " + boss.age + " years old.");
</script>
2. 把方法添加到 JavaScript 对象
<!DOCTYPEhtml>
<html>
<body>
<script>
functionperson(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName; / this.changeName=function(name)
function changeName(name) {
{ this.lastname=name;
this.lastname=name; }
}
myMother=newperson("Steve","Jobs",56,"green");
myMother.changeName("Ballmer");
document.write(myMother.lastname);
</script>
</body>
</html>
3.JavaScript 数字
极大或极小的数字可通过科学(指数)计数法来写:
var y=123e5; // 12300000
var z=123e-5; // 0.00123
整数(不使用小数点或指数计数法)最多为 15 位。
小数的最大位数是 17,但是浮点运算并不总是 100% 准确:
4.正则表达式RegExp
RegExp 对象用于存储检索模式。
通过 new 关键词来定义 RegExp 对象。以下代码定义了名为 patt1 的 RegExp 对象,其模式是 "e":
var patt1=new RegExp("e");
当使用该 RegExp 对象在一个字符串中检索时,将寻找的是字符 "e"。
RegExp 对象有 3 个方法:
test():检索字符串中的指定值。返回值是 true 或 false。
varpatt1=new RegExp("e");
document.write(patt1.test("Thebest things in life are free"));
exec():检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
varpatt1=new RegExp("e");
document.write(patt1.exec("Thebest things in life are free"));
可以向 RegExp 对象添加第二个参数,以设定检索。例如,如果需要找到所有某个字符的所有存在,则可以使用 "g" 参数 ("global")。
在使用 "g" 参数时,exec() 的工作原理如下:
找到第一个 "e",并存储其位置
如果再次运行 exec(),则从存储的位置开始检索,并找到下一个 "e",并存储其位置
var patt1=new RegExp("e","g");
do
{
result=patt1.exec("The best things in life are free");
document.write(result);
}
while (result!=null)
compile():用于改变 RegExp,可以改变检索模式,也可以添加或删除第二个参数。
varpatt1=new RegExp("e");
document.write(patt1.test("Thebest things in life are free"));
patt1.compile("d");
document.write(patt1.test("Thebest things in life are free"));
由于字符串中存在 "e",而没有 "d",以上代码的输出是:
truefalse