JS允许自定义对象
1.定义并创建对象实例
<script>
people = new Object();//Object 是最大得对象
people.name = "Edward";
people.age = 24;
</script>
或
<script>
people = {name:"Edward",age:24};
</script>
2.使用函数来定义对象,然后创建新的对象实例
<script>
function people(name,age){
this.name = name;
this.age = age;
}
son = new people("Edward",24);
document.write("name:"+son.name+",age:"+son.age);
</script>
内置对象
String对象
String对象用于处理已有的字符串
字符串可以使用双引号或单引号
1.在字符串中查找字符串:indexOf()
var str = "Hello world";
document.write("字符串的长度:"+str.length);
document.write(str.indexOf("world"));//有则返回第一个字母的位置,反之返回“-1”
2.内容匹配:match()
var str = "Hello world";
document.write("字符串的长度:"+str.length);
document.write(str.match("world"));//有则输出,反之返回null
3.替换内容: replace()
var str = "Hello world";
document.write("字符串的长度:"+str.length);
document.write(str.replace("被替换值","替换值"));//参数写正确
4.字符串大小写转换:toUpperCase()/toLowerCase()
var str = "Hello world";
document.write("字符串的长度:"+str.length);
document.write(str.toUpperCase());
document.write(str.toLowerCase());
5.字符串转为数组:strong>split()
var str1 = "hello,world";
var s = str1.split(",");
document.write(s[0]);
属性:length prototype constructor
方法:charAt() charCodeAt() concat() fromCharCode() indexOf()
lastIndexOf() match() replace() search() slice()
substring() substr() valueOf() toLowerCase()
toUpperCase() split()
Date对象###
用于处理日期和时间
常用方法:
getFullYear(): 获取年份
getTime(): 获取毫秒
setFullYear(): 设置具体的日期,三个参数,年月日
getDay(): 获取星期 时钟
<script>
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById("timetxt").innerHTML = h+":"+m+":"+s;
t = setTimeout(function(){
startTime();
},1000);
}
function checkTime(i){
if(i<10){
i = "0"+i;
}
return i;
}
</script>
<div id="timetxt"></div>
Array对象###
常用的方法:
concat(): 合并数组
sort(): 排序
push(): 末尾追加元素
reverse(): 数组元素翻转
<script>
var a = ["hello","world"];
var b = ["Edward","kat"];
var c = a.concat(b);//合并数组
document.write(c);
var d = ["a","d","c","b"];
document.write(a.sort());//默认升序排列
document.write(a.sort(function(a,b){
return b-a }));//默认升序排列
a.push("c");
document.write(a);
a.reverse();
document.write(a);
</script>
Math对象###
常用方法:
round(): 四舍五入
random(): 返回0~1之间的随机数
max(): 返回最大值
min(): 返回最小值
abs(): 返回绝对值
<script>
document.write(Math.round(2.3));
</script>