JS允許自定義對象
1.定義并創(chuàng)建對象實(shí)例
<script>
people = new Object();//Object 是最大得對象
people.name = "Edward";
people.age = 24;
</script>
或
<script>
people = {name:"Edward",age:24};
</script>
2.使用函數(shù)來定義對象敏释,然后創(chuàng)建新的對象實(shí)例
<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>
內(nèi)置對象
String對象
String對象用于處理已有的字符串
字符串可以使用雙引號或單引號
1.在字符串中查找字符串:indexOf()
var str = "Hello world";
document.write("字符串的長度:"+str.length);
document.write(str.indexOf("world"));//有則返回第一個字母的位置析恢,反之返回“-1”
2.內(nèi)容匹配:match()
var str = "Hello world";
document.write("字符串的長度:"+str.length);
document.write(str.match("world"));//有則輸出,反之返回null
3.替換內(nèi)容: replace()
var str = "Hello world";
document.write("字符串的長度:"+str.length);
document.write(str.replace("被替換值","替換值"));//參數(shù)寫正確
4.字符串大小寫轉(zhuǎn)換:toUpperCase()/toLowerCase()
var str = "Hello world";
document.write("字符串的長度:"+str.length);
document.write(str.toUpperCase());
document.write(str.toLowerCase());
5.字符串轉(zhuǎn)為數(shù)組: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(): 設(shè)置具體的日期,三個參數(shù)斩箫,年月日
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(): 合并數(shù)組
sort(): 排序
push(): 末尾追加元素
reverse(): 數(shù)組元素翻轉(zhuǎn)
<script>
var a = ["hello","world"];
var b = ["Edward","kat"];
var c = a.concat(b);//合并數(shù)組
document.write(c);
var d = ["a","d","c","b"];
document.write(a.sort());//默認(rèn)升序排列
document.write(a.sort(function(a,b){
return b-a }));//默認(rèn)升序排列
a.push("c");
document.write(a);
a.reverse();
document.write(a);
</script>
Math對象###
常用方法:
round(): 四舍五入
random(): 返回0~1之間的隨機(jī)數(shù)
max(): 返回最大值
min(): 返回最小值
abs(): 返回絕對值
<script>
document.write(Math.round(2.3));
</script>