JavaScript基础(4)

来源:互联网 发布:法律硕士就业前景知乎 编辑:程序博客网 时间:2024/06/05 18:13

1.JavaScript对象

1.1创建对象

person=new Object();
person.firstName="zyf";
或者
person={firstName:"zyf"};
或者对象构造器
function person(firstName,lastName,color){
this.firstName=firstName;
this.lastName=lastName;
this.color=color;
}
var myFrield=new person("s","kk","blue");

1.2JavaScript对象
Number:
String:length,indexOf() ,match() ,replace()
Date: new Date(),
Array:new Array(),concat(),join(),sort();
Boolean
Math:round(),max(),min(),random();


2.JavaScript正则表达式

1.regExp
定义:var patt1=new RegExp("e");


2.test()

test() 方法检索字符串中的指定值。返回值是 true 或 false。

例子:

var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free")); 

由于该字符串中存在字母 "e",以上代码的输出将是:

true

3.exec()

exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。

例子 1:

var patt1=new RegExp("e");document.write(patt1.exec("The best things in life are free")); 

由于该字符串中存在字母 "e",以上代码的输出将是:

e

您可以向 RegExp 对象添加第二个参数,以设定检索。例如,如果需要找到所有某个字符的所有存在,则可以使用 "g" 参数 ("global")。

如需关于如何修改搜索模式的完整信息,请访问我们的 RegExp 对象参考手册。

在使用 "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) 

由于这个字符串中 6 个 "e" 字母,代码的输出将是:

eeeeeenull

4.compile()

compile() 方法用于改变 RegExp。

compile() 既可以改变检索模式,也可以添加或删除第二个参数。

例子:

var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));patt1.compile("d");document.write(patt1.test("The best things in life are free"));

由于字符串中存在 "e",而没有 "d",以上代码的输出是:

truefalse



0 0