我們在寫程式時陣列是很常用到的東西,我們來看看js有提供那些方法來對陣列做改動。
typeof(obj),可得知obj的型態,會輸出string、number、boolean、object等....。
text:"asd",
console.log(typeof(this.text))//輸出string
可以用來判斷字串或陣列的長度
originarray:["one","two","three","four","five","six"],
console.log(this.originarray.length)//輸出6
text:"asd"
console.log(this.text.length)//輸出3
對指定的陣列增加值,從該陣列的最後一筆開始新增。
arraytest:["new"]
this.arraytest.push("pushtest")
console.log(this.arraytest)//輸出["new","pushtest"]
對指定的陣列增加值,從該陣列的第一筆開始新增。
arraytest:["new"]
this.arraytest.unshift("unshifttest")
console.log(this.arraytest)//輸出["unshifttest",new"]
判斷陣列有無指定值,若有回傳true,若否回傳false。
originarray:["one","two","three","four","five","six"],
console.log(this.originarray.includes("two"))//輸出true
也可傳入參數,表示從該陣列的索引值開始尋找。
console.log(this.originarray.includes("two",2))//輸出false
console.log(this.originarray.includes("two",1))//輸出true
判斷陣列有無指定值,若有回傳大於等於0的數值,該數值表示陣列的索引值,若否回傳-1。
originarray:["one","two","three","four","five","six"],
console.log(this.originarray.indexOf("three"))//輸出2
可傳入參數,表示從該陣列的索引值開始尋找。
console.log(this.originarray.indexOf("three",2))//輸出2
console.log(this.originarray.indexOf("three",3))//輸出-1
將陣列做反轉。
originarray:["one","two","three","four","five","six"],
console.log(this.originarray)
//輸出["one", "two", "three", "four", "five", "six"]
console.log(this.originarray.reverse())
//輸出["six", "five", "four", "three", "two", "one"]