簡介:
在JavaScript中除了null和undefined以外其他的數據類型都被定義成了對象,也可以用創建對象的方法定義變量,String、Math、Array、Date、RegExp都是JavaScript中重要的內置對象,在JavaScript程序大多數功能都是基於對象實現的
<script language="javascript"> var aa=Number.MAX_VALUE; //利用數字對象獲取可表示最大數 var bb=new String("hello JavaScript"); //創建字符串對象 var cc=new Date(); //創建日期對象 var dd=new Array("星期一","星期二","星期三","星期四"); //數組對象 </script>
一、string對象(字符串)
1.字符串對象創建
字符串創建(兩種方式)
① 變量 = “字符串”
② 字串串對象名稱 = new String (字符串)
// ========================
// 字符串對象的創建有兩種方式
// 方式一
var s = 'sffghgfd';
// 方式二
var s1 = new String(' hel lo ');
console.log(s,s1);
console.log(typeof(s)); //object類型
console.log(typeof (s1)); //string類型
2.字符串對象的屬性和函數
-------屬性
x.length ----獲取字符串的長度
------方法
x.toLowerCase() ----轉為小寫
x.toUpperCase() ----轉為大寫
x.trim() ----去除字符串兩邊空格
----字符串查詢方法
x.charAt(index) ----str1.charAt(index);----獲取指定位置字符,其中index為要獲取的字符索引
x.indexOf(index)----查詢字符串位置
x.lastIndexOf(findstr)
x.match(regexp) ----match返回匹配字符串的數組,如果沒有匹配則返回null
x.search(regexp) ----search返回匹配字符串的首字符位置索引
示例:
var str1="welcome to the world of JS!";
var str2=str1.match("world");
var str3=str1.search("world");
alert(str2[0]); // 結果為"world"
alert(str3); // 結果為15
----子字符串處理方法
x.substr(start, length) ----start表示開始位置,length表示截取長度
x.substring(start, end) ----end是結束位置
x.slice(start, end) ----切片操作字符串
示例:
var str1="abcdefgh";
var str2=str1.slice(2,4);
var str3=str1.slice(4);
var str4=str1.slice(2,-1);
var str5=str1.slice(-3,-1);
alert(str2); //結果為"cd"
alert(str3); //結果為"efgh"
alert(str4); //結果為"cdefg"
alert(str5); //結果為"fg"
x.replace(findstr,tostr) ---- 字符串替換
x.split(); ----分割字符串
var str1="一,二,三,四,五,六,日";
var strArray=str1.split(",");
alert(strArray[1]);//結果為"二"
x.concat(addstr) ---- 拼接字符串
方法的使用

1 <script> 2 // ======================== 3 // 字符串對象的創建有兩種方式 4 // 方式一 5 var s = 'sffghgfd'; 6 // 方式二 7 var s1 = new String(' hel lo '); 8 console.log(s,s1); 9 console.log(typeof(s)); //object類型 10 console.log(typeof (s1)); //string類型 11 12 // ====================== 13 // 字符串對象的屬性和方法 14 // 1.字符串就這么一個屬性 15 console.log(s.length); //獲取字符串的長度 16 17 // 2.字符串的方法 18 console.log(s.toUpperCase()) ; //變大寫 19 console.log(s.toLocaleLowerCase()) ;//變小寫 20 console.log(s1.trim()); //去除字符串兩邊的空格(和python中的strip方法一樣,不會去除中間的空格) 21 //// 3.字符串的查詢方法 22 console.log(s.charAt(3)); //獲取指定索引位置的字符 23 console.log(s.indexOf('f')); //如果有重復的,獲取第一個字符的索引,如果沒有你要找的字符在字符串中沒有就返回-1 24 console.log(s.lastIndexOf('f')); //如果有重復的,獲取最后一個字符的索引 25 var str='welcome to the world of JS!'; 26 var str1 = str.match('world'); //match返回匹配字符串的數組,如果沒有匹配則返回null 27 var str2 = str.search('world');//search返回匹配字符串從首字符位置開始的索引,如果沒有返回-1 28 console.log(str1);//打印 29 alert(str1);//彈出 30 console.log(str2); 31 alert(str2); 32 33 34 // ===================== 35 // 子字符串處理方法 36 var aaa='welcome to the world of JS!'; 37 console.log(aaa.substr(2,4)); //表示從第二個位置開始截取四個 38 console.log(aaa.substring(2,4)); //索引從第二個開始到第四個,注意顧頭不顧尾 39 //切片操作(和python中的一樣,都是顧頭不顧尾的) 40 console.log(aaa.slice(3,6));//從第三個到第六個 41 console.log(aaa.slice(4)); //從第四個開始取后面的 42 console.log(aaa.slice(2,-1)); //從第二個到最后一個 43 console.log(aaa.slice(-3,-1)); 44 45 46 // 字符串替換、、 47 console.log(aaa.replace('w','c')); //字符串替換,只能換一個 48 //而在python中全部都能替換 49 console.log(aaa.split(' ')); //吧字符串按照空格分割 50 alert(aaa.split(' ')); //吧字符串按照空格分割 51 var strArray = aaa.split(' '); 52 alert(strArray[2]) 53 </script>
二、Array對象(數組)
1.創建數組的三種方式
創建方式1:
var arrname = [元素0,元素1,….]; // var arr=[1,2,3];
創建方式2:
var arrname = new Array(元素0,元素1,….); // var test=new Array(100,"a",true);
創建方式3:
var arrname = new Array(長度);
// 初始化數組對象:
var cnweek=new Array(7);
cnweek[0]="星期日";
cnweek[1]="星期一";
...
cnweek[6]="星期六";
2.數組的屬性和方法

1 // ==================== 2 // 數組對象的屬性和方法 3 var arr = [11,55,'hello',true,656]; 4 // 1.join方法 5 var arr1 = arr.join('-'); //將數組元素拼接成字符串,內嵌到數組了, 6 alert(arr1); //而python中內嵌到字符串了 7 // 2.concat方法(鏈接) 8 var v = arr.concat(4,5); 9 alert(v.toString()) //返回11,55,'hello',true,656,4,5 10 // 3.數組排序reserve sort 11 // reserve:倒置數組元素 12 var li = [1122,33,44,20,'aaa',2]; 13 console.log(li,typeof (li)); //Array [ 1122, 33, 44, 55 ] object 14 console.log(li.toString(), typeof(li.toString())); //1122,33,44,55 string 15 alert(li.reverse()); //2,'aaa',55,44,33,1122 16 // sort :排序數組元素 17 console.log(li.sort().toString()); //1122,2,20,33,44,aaa 是按照ascii碼值排序的 18 // 如果就想按照數字比較呢?(就在定義一個函數) 19 // 方式一 20 function intsort(a,b) { 21 if (a>b){ 22 return 1; 23 } 24 else if (a<b){ 25 return -1; 26 } 27 else{ 28 return 0; 29 } 30 } 31 li.sort(intsort); 32 console.log(li.toString());//2,20,33,44,1122,aaa 33 34 // 方式二 35 function Intsort(a,b) { 36 return a-b; 37 } 38 li.sort(intsort); 39 console.log(li.toString()); 40 // 4.數組切片操作 41 //x.slice(start,end); 42 var arr1=['a','b','c','d','e','f','g','h']; 43 var arr2=arr1.slice(2,4); 44 var arr3=arr1.slice(4); 45 var arr4=arr1.slice(2,-1); 46 alert(arr2.toString());//結果為"c,d" 47 alert(arr3.toString());//結果為"e,f,g,h" 48 alert(arr4.toString());//結果為"c,d,e,f,g" 49 // 5.刪除子數組 50 var a = [1,2,3,4,5,6,7,8]; 51 a.splice(1,2); 52 console.log(a) ;//Array [ 1, 4, 5, 6, 7, 8 ] 53 // 6.數組的push和pop 54 // push:是將值添加到數組的結尾 55 var b=[1,2,3]; 56 b.push('a0','4'); 57 console.log(b) ; //Array [ 1, 2, 3, "a0", "4" ] 58 59 // pop;是講數組的最后一個元素刪除 60 b.pop(); 61 console.log(b) ;//Array [ 1, 2, 3, "a0" ] 62 //7.數組的shift和unshift 63 unshift: 將值插入到數組的開始 64 shift: 將數組的第一個元素刪除 65 b.unshift(888,555,666); 66 console.log(b); //Array [ 888, 555, 666, 1, 2, 3, "a0" ] 67 68 b.shift(); 69 console.log(b); //Array [ 555, 666, 1, 2, 3, "a0" ] 70 // 8.總結js的數組特性 71 // java中的數組特性:規定是什么類型的數組,就只能裝什么類型.只有一種類型. 72 // js中的數組特性 73 // js中的數組特性1:js中的數組可以裝任意類型,沒有任何限制. 74 // js中的數組特性2: js中的數組,長度是隨着下標變化的.用到多長就有多長. 75 </script>
三、date對象(日期)
1.創建date對象
創建date對象
// 方式一:
var now = new Date();
console.log(now.toLocaleString()); //2017/9/25 下午6:37:16
console.log(now.toLocaleDateString()); //2017/9/25
// 方式二
var now2 = new Date('2004/2/3 11:12');
console.log(now2.toLocaleString()); //2004/2/3 上午11:12:00
var now3 = new Date('08/02/20 11:12'); //2020/8/2 上午11:12:00
console.log(now3.toLocaleString());
//方法3:參數為毫秒數
var nowd3=new Date(5000);
alert(nowd3.toLocaleString( ));
alert(nowd3.toUTCString()); //Thu, 01 Jan 1970 00:00:05 GMT
2.Date對象的方法—獲取日期和時間
獲取日期和時間
getDate() 獲取日
getDay () 獲取星期
getMonth () 獲取月(0-11)
getFullYear () 獲取完整年份
getYear () 獲取年
getHours () 獲取小時
getMinutes () 獲取分鍾
getSeconds () 獲取秒
getMilliseconds () 獲取毫秒
getTime () 返回累計毫秒數(從1970/1/1午夜)
實例練習
1.打印這樣的格式2017-09-25 17:36:星期一

1 function foo() { 2 var date = new Date(); 3 var year = date.getFullYear(); 4 var month = date.getMonth(); 5 var day= date.getDate(); 6 var hour = date.getHours(); 7 var min= date.getMinutes(); 8 var week = date.getDay(); 9 console.log(week); 10 var arr=['星期日','星期一','星期二','星期三','星期四','星期五','星期六']; 11 console.log(arr[week]); 12 // console.log(arr[3]); 13 console.log(year+'-'+chengemonth(month+1)+'-'+day+' '+hour+':'+min+':'+arr[week]) 14 } 15 function chengemonth(num) { 16 if (num<10){ 17 return '0'+num 18 } 19 else{ 20 return num 21 } 22 } 23 foo() 24 console.log(foo()) //沒有返回值返回undefined 25 26 //三元運算符 27 console.log(2>1?2:1)
2.設置日期和時間

1 //設置日期和時間 2 //setDate(day_of_month) 設置日 3 //setMonth (month) 設置月 4 //setFullYear (year) 設置年 5 //setHours (hour) 設置小時 6 //setMinutes (minute) 設置分鍾 7 //setSeconds (second) 設置秒 8 //setMillliseconds (ms) 設置毫秒(0-999) 9 //setTime (allms) 設置累計毫秒(從1970/1/1午夜) 10 11 var x=new Date(); 12 x.setFullYear (1997); //設置年1997 13 x.setMonth(7); //設置月7 14 x.setDate(1); //設置日1 15 x.setHours(5); //設置小時5 16 x.setMinutes(12); //設置分鍾12 17 x.setSeconds(54); //設置秒54 18 x.setMilliseconds(230); //設置毫秒230 19 document.write(x.toLocaleString( )+"<br>"); 20 //返回1997年8月1日5點12分54秒 21 22 x.setTime(870409430000); //設置累計毫秒數 23 document.write(x.toLocaleString( )+"<br>"); 24 //返回1997年8月1日12點23分50秒
3.日期和時間的轉換:

1 日期和時間的轉換: 2 3 getTimezoneOffset():8個時區×15度×4分/度=480; 4 返回本地時間與GMT的時間差,以分鍾為單位 5 toUTCString() 6 返回國際標准時間字符串 7 toLocalString() 8 返回本地格式時間字符串 9 Date.parse(x) 10 返回累計毫秒數(從1970/1/1午夜到本地時間) 11 Date.UTC(x) 12 返回累計毫秒數(從1970/1/1午夜到國際時間)
四、Math對象(數學有關的)
//該對象中的屬性方法 和數學有關.
abs(x) 返回數的絕對值。
exp(x) 返回 e 的指數。
floor(x)對數進行下舍入。
log(x) 返回數的自然對數(底為e)。
max(x,y) 返回 x 和 y 中的最高值。
min(x,y) 返回 x 和 y 中的最低值。
pow(x,y) 返回 x 的 y 次冪。
random() 返回 0 ~ 1 之間的隨機數。
round(x) 把數四舍五入為最接近的整數。
sin(x) 返回數的正弦。
sqrt(x) 返回數的平方根。
tan(x) 返回角的正切。
使用

五、Function對象(重點)
1.函數的定義
function 函數名 (參數){ <br> 函數體; return 返回值; }
功能說明:
可以使用變量、常量或表達式作為函數調用的參數
函數由關鍵字function定義
函數名的定義規則與標識符一致,大小寫是敏感的
返回值必須使用return
Function 類可以表示開發者定義的任何函數。
用 Function 類直接創建函數的語法如下:
var 函數名 = new Function("參數1","參數n","function_body");
雖然由於字符串的關系,第二種形式寫起來有些困難,但有助於理解函數只不過是一種引用類型,它們的行為與用 Function 類明確創建的函數行為是相同的。
示例:
var func2 = new Function('name',"alert(\"hello\"+name);");
func2('haiyan');
注意:js的函數加載執行與python不同,它是整體加載完才會執行,所以執行函數放在函數聲明上面或下面都可以:
f(); --->OK
function f(){
console.log("hello")
} f();//----->OK
//
2.Function 對象的屬性
如前所述,函數屬於引用類型,所以它們也有屬性和方法。
比如,ECMAScript 定義的屬性 length 聲明了函數期望的參數個數。
alert(func1.length)
3.Function 的調用

1 // ========================函數的調用 2 function fun1(a,b) { 3 console.log(a+b) 4 } 5 fun1(1,2);// 3 6 fun1(1,2,3,4); //3 7 fun1(1); //NaN 8 fun1(); //NaN 9 console.log(fun1()) 10 11 // ===================加個知識點 12 var d="yuan"; 13 d=+d; 14 alert(d);//NaN:屬於Number類型的一個特殊值,當遇到將字符串轉成數字無效時,就會得到一個NaN數據 15 alert(typeof(d));//Number 16 NaN特點: 17 var n=NaN; 18 alert(n>3); 19 alert(n<3); 20 alert(n==3); 21 alert(n==NaN); 22 alert(n!=NaN);//NaN參與的所有的運算都是false,除了!= 23 24 =============一道面試題、、 25 function a(a,b) { 26 console.log(a+b); 27 } 28 var a=1; 29 var b=2; 30 a(a,b) //如果這樣的話就會報錯了,不知道是哪個a了。
4.函數的內置對象arguments

1 // 函數的內置對象arguments,相當於python中的動態參數 2 function add(a,b){ 3 console.log(a+b);//3 4 console.log(arguments.length);//2 5 console.log(arguments);//[1,2] 6 } 7 add(1,2) 8 // ------------------arguments的用處1 ------------------ 9 function ncadd() { 10 var sum = 0; 11 for (var i =0;i<arguments.length;i++){ 12 // console.log(i);//打印的是索引 13 // console.log(arguments);//Arguments { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 等 2 項… } 14 console.log(arguments[i]);//1,2,3,4,5 15 sum +=arguments[i] 16 } 17 return sum 18 } 19 ret = ncadd(1,2,3,4,5,6); 20 console.log(ret); 21 22 23 // ------------------arguments的用處2 ------------------ 24 25 function f(a,b,c){ 26 if (arguments.length!=3){ 27 throw new Error("function f called with "+arguments.length+" arguments,but it just need 3 arguments") 28 } 29 else { 30 alert("success!") 31 } 32 } 33 34 f(1,2,3,4,5)
5.匿名函數

1 / ======================= 2 // 匿名函數 3 var func = function(arg){ 4 return "tony"; 5 }; 6 7 // 匿名函數的應用 8 (function(){ 9 alert("tony"); 10 } )() 11 12 (function(arg){ 13 console.log(arg); 14 })('123')
六、BOM對象(重點)
window對象
所有瀏覽器都支持 window 對象。
概念上講.一個html文檔對應一個window對象.
功能上講: 控制瀏覽器窗口的.
使用上講: window對象不需要創建對象,直接使用即可.
1.對象方法
alert() 顯示帶有一段消息和一個確認按鈕的警告框。
confirm() 顯示帶有一段消息以及確認按鈕和取消按鈕的對話框。
prompt() 顯示可提示用戶輸入的對話框。
open() 打開一個新的瀏覽器窗口或查找一個已命名的窗口。
close() 關閉瀏覽器窗口。
setInterval() 按照指定的周期(以毫秒計)來調用函數或計算表達式。
clearInterval() 取消由 setInterval() 設置的 timeout。
setTimeout() 在指定的毫秒數后調用函數或計算表達式。
clearTimeout() 取消由 setTimeout() 方法設置的 timeout。
scrollTo() 把內容滾動到指定的坐標。
2.方法使用
<script> window.open(); window.alert(123); window.confirm(546); window.prompt(147258); window.close(); // =============定時器 function foo() { console.log(123) } var ID = setInterval(foo,1000); //每個一秒執行一下foo函數,如果你不取消 //,就會一直執行下去 clearInterval(ID) //還沒來得及打印就已經停掉了 // ===================== function foo() { console.log(123) } var ID=setTimeout(foo,1000); clearTimeout(ID)

1 // 定時器實例 2 // var date = new Date(); //Date 2017-09-25T12:20:25.536Z 3 // console.log(date); 4 // var date1 = date.toLocaleString(); 5 // console.log(date1); //2017/9/25 下午8:20:59 6 7 function foo() { 8 var date = new Date(); 9 var date = date.toLocaleString();//吧日期字符串轉換成字符串形式 10 var ele = document.getElementById('timer') //從整個html中找到id=timer的標簽,也就是哪個input框 11 12 ele.value = date; 13 console.log(ele) //ele是一個標簽對象 14 // value值是什么input框就顯示什么 15 } 16 var ID; 17 function begin() { 18 if (ID==undefined){ 19 foo(); 20 ID = setInterval(foo,1000) 21 } 22 } 23 24 function end() { 25 clearInterval(ID); 26 console.log(ID); 27 ID = undefined 28 }
七、DOM對象(重點)