首頁 >web前端 >js教程 >js中物件的宣告方式以及陣列的一些用法範例_基礎知識

js中物件的宣告方式以及陣列的一些用法範例_基礎知識

WBOY
WBOY原創
2016-05-16 17:09:41862瀏覽
複製程式碼 程式碼如下:




New Document




<script> <BR>//定義一個列印函數<BR>var $=function(str){ <BR>document.write(str); <BR>document .write("<br/>"); <BR>} <BR>//定義列印陣列函數<BR>var _=function(arr){ <BR>for(var tmp in arr) <BR>{ <BR>$(arr[tmp]); <BR>} <BR>} <BR>//定義一個學生物件<BR>var stu=new Object(); <br><br>//聲明屬性和行為<BR>stu.id=16; <BR>stu.name='燈幣'; <BR>stu.age=function(){ <BR>return this.id; <BR>} <br><br> //印出學生的資訊<BR>$(stu.id); <BR>$(stu.name); <BR>$(stu.age());//呼叫時要加括號<br><br>stu.sex='女'; //新增屬性<BR>$(stu.sex); //印出新加入的屬性<br><br>//方案2: <BR>function Student(id,名) <BR>{ <BR>this.id=id; <BR>this.name=name; <BR>this.getAge=function(){ <BR>return this.id; <BR>} <br>} <br> <br>} <br><BR>//使用<BR>var stu2=new Student(1,'揚頓'); <BR>$(stu2.id); <BR>$(stu2.name); <BR>$(stu2.getAge()); <BR>//再定義一個屬性<BR>stu2.sex='偽娘'; <BR>$(stu2.sex); <BR>//動態語言如何跨域? <BR>Student.prototype.address="阿富汗"; <BR>$(stu2.address); <BR>$("stu2_1 begin..."); <BR>var stu2_1 =new Student(1,'揚頓'); <BR>$(stu2_1.id); <BR>$(stu2_1.name); <BR>$(stu2_1.getAge()); <BR>$(stu2_1.sex); <BR>$ (stu2_1.address); //跨域訪問,b物件訪問a物件的屬性<BR>//在定義<br>$("stu2_1 end..."); <br><BR>//方案3 :json <BR>var stu3={id:1,name:'毛炎炎',getName:function(){return this.name;}}; <BR>$(stu3.id); <BR>$(stu3 .name); <br>$(stu3.getName()); <br><br>//var stu2 <br><BR>//js裡面的函數很多跟裡面函數同名<BR>var str1= new String("abcd") <BR>var str2="asdf"; <BR>$(str1.indexOf('c')); <BR>$(str1.charAt(3)); <BR>$ ( str2.charAt(3)); <br>$("absdf".substring(2,4)); <br><BR>var day=new Date(); <BR>$(day.getYear()) ; <br>$(day.toLocaleString()); <br><BR><BR>//再談陣列<BR>var arr1=new Array(3); <BR>arr1[0]=10; <BR>arr1[1]=20; <BR>arr1[2]=3; <BR>_(arr1); <BR>arr1[3]=4; <BR>// <br>_(arr1); <br><BR>//陣列2 <BR>var arr2=new Array(234,345,2354,2134,234); <br>_(arr2); <br><BR>///陣列3 <BR> arr3=new Array(); <BR>arr3[0]=10; <BR>arr3[1]=20; <BR>arr3[2]=3; <br>_(arr3); <br><BR>//陣列4.推薦寫法<BR>var arr4=[]; <BR>arr4[0]=10; <BR>arr4[1]=20; <BR>arr4[2]=3; <br> _(arr4); <br><BR>//陣列5.推薦寫法<BR>var arr5=[3254,43,532,45,2345]; <br>_(arr5); <br><BR>function add (i,j){ <BR>return i j; <br>} <br><BR>function add(i,j,k){ <BR>return i j k; <br>} <br><br>$( add(1,2));//參數數量自動辨識<br><BR>var Person=function(id,name) <BR>{ <BR>this.id=id;//public <BR>this .name=name;//public <BR>var i=1;//private <BR>function test(){//private <BR>alert('asdf'); <BR>} <BR>this.t =function()//public <BR>{ <BR>return 1; <BR>} <BR>} <BR>var p=new Person(1,"陳新"); <BR>$(p.id ); <BR>$(p.name); <BR>$(p.t());//正常存取<BR>$(p.test()); //不能存取<BR></script>



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn