6、 js内置的對象
6.1 數組
<script type="text/javascript">
//聲明出數組,并附上初始值
//var arr=[1,2,3];
var arr=new Array();
//js的長度可以變化,把4放入到數組裡面。
arr.push(4);
arr[1]=1;
/*for(var i=0;i<arr.length;i++){
console.log(arr[i]);
}*/
//這種for循環,循環到的i值是數組的下标,而不是元素值
for(var i in arr){
console.log(arr[i]);
}
</script>
或者我們先建立出數組對象,再往數組裡面放元素:
var arr=new Array();
arr.push(2);
arr[1]=1;
6.2 字元串
常見的方法:
indexOf():擷取字元串的下标
subString():截斷字元串。
Trim():去除左右空格
Split():把字元串拆分成數組。
6.3 日期
<script type="text/javascript">
var d=new Date();//系統目前時間
alert(d);
var y=d.getFullYear();//擷取四位的年
var m=d.getMonth();//擷取月份,月份從0開始,要得到目前月份需要+1
var day=d.getDay();//擷取到星期幾
alert(day);
</script>
6.4 Json
Json就是Js中的對象。Ajax會用到json。
var person={屬性名:屬性值,屬性名:屬性值,函數名:function(){函數體}};
<script type="text/javascript">
//定義json對象
var stu={
name:"zhangsan",
age:20,//屬性
study:function(){
console.log("------good good study----------");
},//對象的方法
say:function(){
console.log("----------你好,我叫"+this.name+"-------");
}
};
stu.say();//調用say方法
var a=stu.age;//調用age屬性
console.log(a);
</script>
7 Dom操作
通過js代碼,
操作元素(html的标簽)的屬性,增加或者修改屬性值,或者修改元素的内容。
Dom:document object model(文檔對象模型)。
浏覽器在解析html文檔的時候,會把html源碼分析成一個模型圖,這個圖形就被稱為文檔結構模型。
//擷取到dom模型上面的dom元素。
var obj=document.getElementById(“元素的id值”);
Dom操作案例:
通過按鈕實作複選框的選中和不選中
<script type="text/javascript">
function test(){
var name = document.getElementsByName("f");
for(var i=0;i<name.length;i++){
name[i].checked=document.getElementById("ch").checked;
}
}
</script>
</head>
<body>
<div style="margin:0 auto;width: 400px;height: 200px;" id="test" >
<input type="checkbox" id="ch" onclick="test()"/>全選<br/>
<input type="checkbox" name="f">西瓜<br/>
<input type="checkbox" name="f">蘋果<br/>
<input type="checkbox" name="f">香蕉<br/>
<input type="checkbox" name="f">橘子<br/>
</div>
</body>
<script type="text/javascript">
function test(obj){
obj.style="color:red";
}
function test2(obj) {
obj.style="color:black";
}
</script>
</head>
<body>
<div style="margin:0 auto;width: 400px;height: 200px;" id="test" >
<br/>
<h1 onmouseover="test(this)" onmouseout="test2(this)" id="t1">張山</h1>
<h1 onmouseover="test(this)" onmouseout="test2(this)" id="t2">李四</h1>
<h1 onmouseover="test(this)" onmouseout="test2(this)" id="t3">王五</h1>
<h1 onmouseover="test(this)" onmouseout="test2(this)" id="t4">趙柳</h1>
<h1 onmouseover="test(this)" onmouseout="test2(this)" id="t5">馬起</h1>
</div>
</body>
12 Bom操作
- js的基本文法。函數
- Dom操作。控制元素,對元素進行修改。
- Bom操作。對整個浏覽器對象的操作。包括重新整理,後退,位址欄的操作,視窗的彈出。