DIV CSS 佈局教程網

slice:取出陣列中的一段而不動到原本
編輯:關於JavaScript     

slice() 用來擷取陣列的某個區間,回傳一個新陣列,原本的陣列完全不會被改動。這讓它成為資料處理中非常安全好用的一把刀。

範例:取出第二與第三個元素

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to extract the second and the third elements from the array.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    var citrus = fruits.slice(1, 3);

    var x = document.getElementById("demo");
    x.innerHTML = citrus;
}
</script>
</body>
</html>

輸出:

Orange,Lemon

那個「頭含尾不含」的規則

array.slice(beginIndex, endIndex);

slice(1, 3) 取出索引 1 與 2 的元素,不包含索引 3。這看起來反直覺,但它是刻意的設計:讓 arr.slice(0, n).length 剛好等於 n,計算上不會有 ±1 的困擾。

省略參數的兩種用法

var arr = ["a", "b", "c", "d"];

arr.slice(2);      // ["c", "d"]     從索引 2 取到尾端
arr.slice(-2);     // ["c", "d"]     負數代表從尾端往前算
arr.slice();       // ["a","b","c","d"]  沒有參數 = 淺拷貝整個陣列

最後那一行特別實用:arr.slice() 是 ES5 時代就有的淺拷貝寫法,等同於現代的 [...arr]。當你想傳陣列給某個會改動它的函式、又不希望原資料被動到時,就是靠這個技巧。

注意 slice 是淺拷貝:若元素是物件,複製的是參照,改動副本中的物件屬性仍會影響原件。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved