javascript基礎函數之數組處理函數用法實例匯總
join()
把陣列的所有元素放入一個字串。元素透過指定的分隔符號進行分隔。
例如:
<script type="text/javascript"> var arr = ['item 1', 'item 2', 'item 3']; var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>'; </script>
list結果:
'
- item 1
- item 2
- item 3
這是迄今為止最快的方法!使用原生程式碼(如 join()),不管系統內部做了什麼,通常比非原生快很多。 ——James Padolsey, james.padolsey.com
pop()
#刪除並返回數組的最後一個元素
pop()方法將刪除數組的最後一個元素,把數組長度減1,並且傳回它刪除的元素的值。
如果數組已經為空,則pop()不改變數組,並且傳回undefined值
例如:
<script type="text/javascript"> var arr = ["George", "John", "Thomas"]; document.write(arr + "<br/>"); document.write(arr.pop() + "<br/>"); document.write(arr); </script>
輸出結果:
George,John,Thomas
Thomas
George,John
push()
在陣列的末端新增一個或更多元素,並傳回新的長度
例如:
<script type="text/javascript"> var arr = ["George", "John", "Thomas"]; document.write(arr + "<br/>"); document.write(arr.push("James") + "<br/>"); document.write(arr); </script>
輸出結果:
George,John,Thomas
4
George,John,Thomas,James
unshift()
##向陣列的開頭新增一個或更多元素,並傳回新的長度
例如:<script type="text/javascript"> var arr = ["George", "John", "Thomas"]; document.write(arr + "<br/>"); document.write(arr.unshift("James") + "<br/>"); document.write(arr); </script>
George,John,Thomas
4
James, George,John,Thomas
shift()
#刪除並傳回陣列的第一個元素
例如:<script type="text/javascript"> var arr = ["George", "John", "Thomas"]; document.write(arr + "<br/>"); document.write(arr.shift() + "<br/>"); document.write(arr); </script>
George,John,Thomas
George
#John,Thomas
sort()
對陣列的元素進行排序
該方法預設是按照字元編碼(ASCII)的順序進行排序的
例如:
<script type="text/javascript"> var arr = new Array(6); arr[0] = "John"; arr[1] = "George"; arr[2] = "Thomas"; document.write(arr + "<br/>"); document.write(arr.sort()); </script>
輸出結果:
John,George,Thomas
George,John,Thomas
<script type="text/javascript"> var arr = new Array(6); arr[0] = 10 arr[1] = 5 arr[2] = 40 arr[3] = 25 arr[4] = 1000 arr[5] = 1 document.write(arr + "<br/>"); document.write(arr.sort()); </script>
10,5,40,25,1000,1
1,10,1000,25,40,5
如下:
<script type="text/javascript"> var arr = new Array(6); arr[0] = 10 arr[1] = 5 arr[2] = 40 arr[3] = 25 arr[4] = 1000 arr[5] = 1 document.write(arr + "<br/>"); document.write(arr.sort(function (a, b) {return a - b;}));// 从大到小 </script>
10,5,40,25,1000,1
1,5,10,25,40,1000
如果想要降序排列呢?
將排序規則改為:
function (a, b) {return b - a;}
就OK了
以上是javascript基礎函數之數組處理函數用法實例匯總的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)