JavaScript中的对象:
自定义对象 :开发人员根据自己的需要而定义的新对象
JavaScript内置对象 : JavaScript将一些常用功能预先定义成对象,用户可以直接使用,这就是内置对象 如:字符串对象,数学对象,日期对象,数组对象,正则表达式对象等。
浏览器内置对象:浏览器对象是浏览器根据系统当前的配置和所装载的页面为JavaScript提供的一系列可供使用的对象。如:Window对象,Document对象,History对象等。
创建自定义对象的方式:
使用Object关键字创建对象
例:
// 使用object创建一个对象
var student=new Object()
// document.write(student)
// 给对象student添加属性stuID stuName className
student.stuID="1001"
student.stuName="吕佳琪"
student.className="移动2102"
// 给对象添加了一个函数sayHello
student.sayHello=function(){
document.write("大家好")
document.write("<br />")
}
// document.write(student)
// 对象名,函数名()实现函数的调用
student.sayHello()
document.write(student.stuID,"\t"+student.stuName,"\t"+student.className)
document.write("<br />")
使用function关键字创建对象
例:
// 使用function创建一个对象
function teacher(tid,tname){
// this表示当前对象
this.tid=tid
this.tname=tname
this.eat=function(){
document.write("吃饭")
document.write("<br />")
}
}
var t1=new teacher("1","吕佳琪")
// 使用t1来访问属性和函数
t1.eat()
document.write(t1.tid,"\t"+t1.tname)
其他创建对象的方式
例:
// 其他创建对象的方式
var stu={
stuID:"1002",
stuName:"吕佳琪",
className:"移动2102",
study:function(){
document.write("学习")
document.write("<br />")
}
}
stu.study()
document.write(stu.stuID,stu.stuName,stu.className)
JavaScript内置对象
字符串对象:用于存储一系列字符,使用单引号或双引号包含
数学对象:用于获取各种数学常量及数学函数
日期对象:用于获取或操作各种时间
字符串对象:例
// 字符串对象
var str="Hello World"
// length用来获取字符串的长度
console.log(str.length)
// 返回参数指定索引处的字符
console.log(str.charAt(2))
// 返回参数在字符串中首次出现的位置
console.log(str.indexOf("l"))
// 判断是否包含某个字符
console.log(str.indexOf("b"))
// 返回参数在字符串中最后出现的位置
console.log(str.lastIndexOf("w"))
// 返回字符串中index1和index2之间的字符串
console.log(str.substring(0,5))
// substr():第一个参数指的是索引,第二个参数指的是截取的字符串的长度
console.log(str.substr(1,2)) // 返回字符串中索引为1之后的2个字符
判断邮箱地址格式是否正确 例:
<body>
Email:<input type="text" name="email" id="email" value="" />
<input type="button" name="" id="" value="验证" onclick="checkEmail()"/>
<script type="text/javascript">
// 判断邮箱地址格式是否正确 3439724428@qq.com
function checkEmail(){
// 获取文本框中输入的值
var email=document.getElementById("email").value
if(email.indexOf("@")==-1){
alert("改邮箱地址中不包括@")
}else if(email.indexOf(".")==-1){
alert("改邮箱地址中不包括.")
}else if(email.indexOf("@")>email.indexOf(".")){
alert("邮箱地址中@必须在.的前面")
}else{
alert("邮箱地址正确")
}
}
</script>
</body>