Array.prototype.splice()

Độ tương thích với trình duyệt

Bảng độ tương thích trong trang này được tạo ra từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp cho dữ liệu này, hãy gửi một cho chúng tôi một pull request đến github https://github.com/mdn/browser-compat-data

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Chrome
Full support

1
Edge
Full support

12
Firefox
Full support

1
IE
Full support

4
Opera
Full support

4
Safari
Full support

1
WebView Android
Full support

1
Chrome Android
Full support

18
Firefox Android
Full support

4
Opera Android
Full support

10.1
Safari iOS
Full support

1
Samsung Internet Android
Full support

1.0
nodejs
Full support

0.1.100

API

import { range, slice, SliceArray, SliceString } from 'slice';
const { range, slice, SliceArray, SliceString } = require('slice');

range(stop), range(start, stop, )

  • The value of the first element in the range, or if not specified.
  • The number that, once reached, will terminate the range.
    This value will not be included in the range.
  • The difference between adjacent numbers in the range, or if not specified.
    Negative values for mean that the values in the range are sequentially decreasing.
  • returns: <>

slice(stop), slice(start, stop, )

  • The index of the first element, or the index of the first/last element for positive/negative values of if not specified.
  • The index that, once reached, will terminate the slice.
    If not specified, then the slice will continue until an edge of the iterable has been reached.
  • The gap between adjacent indices in the slice, or if not specified.
    Negative values for mean that the indices in the range are sequentially decreasing.
  • returns: <>

Trình duyệt tương thích

The compatibility table in this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Chrome
Full support

1
Edge
Full support

12
Firefox
Full support

1
IE
Full support

5.5
Notes
Opera
Full support

4
Safari
Full support

1
WebView Android
Full support

1
Chrome Android
Full support

18
Firefox Android
Full support

4
Opera Android
Full support

10.1
Safari iOS
Full support

1
Samsung Internet Android
Full support

1.0
nodejs
Full support

0.1.100

浏览器兼容

The compatibility table in this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Chrome
Full support

1
Edge
Full support

12
Firefox
Full support

1.5
IE
Full support

9
Opera
Full support

9.5
Safari
Full support

3
WebView Android
Full support

≤37
Chrome Android
Full support

18
Firefox Android
Full support

4
Opera Android
Full support

10.1
Safari iOS
Full support

1
Samsung Internet Android
Full support

1.0
nodejs
Full support

0.1.100

說明

 不會修改原本的陣列,而是回傳由原本的陣列淺層複製的元素。 Elements of the original array are copied into the returned array as follows:

  • For object references (and not the actual object), copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
  • For strings, numbers and booleans (not , and objects), copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.

If a new element is added to either array, the other array is not affected.

Array 泛型方法

泛型陣列並非標準且已被棄用,將會在不久之後被去除。 

有時你想將陣列方法用於字串或其他類陣列物件(像是函數 arguments)。藉此操作,你將此字串視為由字元組成的陣列(反之為將其他非陣列視為物件)。如範例,若要確認字串中的每個字元是不是字母,你可能會這樣寫:

function isLetter(character) {
  return character >= 'a' && character <= 'z';
}

if (Array.prototype.every.call(str, isLetter)) {
  console.log("The string '" + str + "' contains only letters!");
}

這種表示法相當浪費,JavaScript 1.6 導入了一個通用方法:

if (Array.every(str, isLetter)) {
  console.log("The string '" + str + "' contains only letters!");
}

也同樣可用於 .

這並非 ECMAScript 的標準,且不被非 Gecko 引擎的瀏覽器支援。你應該將你的物件用  轉為陣列,以標準替代原有的方法;雖然此方法可能不被舊的瀏覽器所支援:

if (Array.from(str).every(isLetter)) { 
  console.log("The string '" + str + "' contains only letters!"); 
}

For People Who Know Python Already

For example, you could run the following without needing to explicitly construct a .

import { range, slice } from 'slice';

// Outputs: 
range(100)slice(10, 15)

Aside from the imports, the actual usage of and here is also valid Python and would produce the same result.
Even if you use Python quite a bit, however, there’s a good chance that you might not that familiar with the explicit usage of like this.
That’s because it’s way more common to use Python’s slice syntax rather than manually instantiating the class.

# These are both equivalent in Python.
range(100)
range(100)

It’s not possible to replicate that exact syntax in JavaScript, but Slice uses a very similar syntax that should be immediately familiar to you if you know Python.
All you need to do is to use double brackets for the indexing and to replace the colons with commas.
The slicing will work exactly as you would expect in Python after that.
It supports negative indexing, empty parameters, extended slices, negative steps, assignment to slices, and the whole shebang.
In fact, part of the test suite actually runs a Python script to perform thousands of slicing operations to verify that the JavaScript results are identical!

Here are a few examples of how the syntax compares between Python and Slice in JavaScript.

Input Python Code JavaScript Code Output

Once you get used to how the Python syntax maps to the double bracket syntax, it becomes quite easy to switch seamlessly between the two.

import { range, SliceArray, SliceString } from 'slice';

// All of the following are equivalent.
range(5);
SliceArray(, 1, 2, 3, 4);
new SliceArray(, 1, 2, 3, 4);
SliceArray.from(, 1, 2, 3, 4);

// The following are also equivalent.
SliceString('hello world');
new SliceString('hello world');

They also support all of the same methods once constructed, but will return slice-able arrays and strings whenever possible.
For example, you can do things like this without needing to worry about converting the method outputs to slice-able objects.

const helloWorld = SliceString('hello world');
// Outputs: 'DLROW OLLEH'
helloWorld.toUpperCase(),,-1;

// Outputs: 
range(5).map(i => i * 2)1,-1;

That’s basically all there is to it!
If you’re ready for a little more Python in your JavaScript, then hop on over to the to get started.

Parameter Values

Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start the slice.
0 = the first element.
If this value is set to a negative number, the function will start slicing that far from the last element.
-2 means start at the second last element of the array.
length Optional. Numeric value. Specifies the length of the returned array.

If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.

preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:

  • true — Preserve keys
  • false —
    Default. Reset keys

精简跨浏览器行为

根据规范,使用 转换宿主对象(如 DOM 对象)时,不必遵循 Mozilla 的默认行为,即可以转化任何符合条件的伪数组宿主对象为数组,IE < 9 没有遵循,而 IE9 + 遵循这个行为,但是稍加改造可以使其在跨浏览器使用时更可靠。只要其他现代浏览器继续支持该行为,目前 IE 9+、FireFox、Chrome、Safari 以及 Opera 都支持,开发者在使用下面代码时遍历 DOM 时就不会被该方法的字面意义误导,即 IE < 9 不能转化 DOM Collections。开发者可以安全地根据语义知道该方法的实际上的标准行为。(下面的代码还修正了 IE 中  方法第二个参数不允许为显式的 / 值的问题,其他现代浏览器,包括 IE9+ 都允许)。

/**
 * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
 * on host objects like NamedNodeMap, NodeList, and HTMLCollection
 * (technically, since host objects have been implementation-dependent,
 * at least before ES2015, IE hasn't needed to work this way).
 * Also works on strings, fixes IE < 9 to allow an explicit undefined
 * for the 2nd argument (as in Firefox), and prevents errors when
 * called on other DOM objects.
 */
(function () {
  'use strict';
  var _slice = Array.prototype.slice;

  try {
    // Can't be used with DOM elements in IE < 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE < 9
    // This will work for genuine arrays, array-like objects, 
    // NamedNodeMap (attributes, entities, notations),
    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
    Array.prototype.slice = function(begin, end) {
      // IE < 9 gets unhappy with an undefined end argument
      end = (typeof end !== 'undefined') ? end : this.length;

      // For native Array objects, we use the native slice function
      if (Object.prototype.toString.call(this) === ''){
        return _slice.call(this, begin, end); 
      }

      // For array like object we handle it ourselves.
      var i, cloned = [],
        size, len = this.length;

      // Handle negative value for "begin"
      var start = begin || 0;
      start = (start >= 0) ? start : Math.max(0, len + start);

      // Handle negative value for "end"
      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
      if (end < 0) {
        upTo = len + end;
      }

      // Actual expected size of the slice
      size = upTo - start;

      if (size > 0) {
        cloned = new Array(size);
        if (this.charAt) {
          for (i = 0; i < size; i++) {
            cloned = this.charAt(start + i);
          }
        } else {
          for (i = 0; i < size; i++) {
            cloned = this;
          }
        }
      }

      return cloned;
    };
  }
}());

Splice ( )

Название этого метода похоже на slice( ): в таких похожих названиях разработчики часто путаются. Метод splice( ) добавляет и удаляет элементы из массива, меняя его. Давайте посмотрим, как добавлять и удалять элементы с помощью метода splice( ):

Удаление элементов

Чтобы удалить элементы, введите элемент, с которого нужно начать (index) и количество элементов, которые нужно удалить (number of elements):

array.splice(index, number of elements);

Параметр Index — это начальная точка удаления элементов. Элементы с порядковым номером меньше заданного параметра Index не будут удалены:

array.splice(2);  // Every element starting from index 2, will be removed

Если не указать второй параметр, все элементы от заданного параметра Index и до конца будут удалены:

only index 0 and 1 are still there

В качестве еще одно примера, я указал 1 в качестве второго параметра: таким образом, каждый раз при повторе метода splice ( ) будет удалять по одному элементу, начиная со второго:

array.splice(2, 1);


Массив до метода splice ( )

Splice ( ) применен один раз:


Элемент 3 удален: следовательно, теперь элемент “hello world” имеет порядковый номер 2

Splice ( ) применен два раза:


На этот раз, был удален элемент “hello world”, потому что его порядковый номер 2

Так можно продолжать до тех пор, пока не останется элементов с порядковым номером 2.

Cú pháp

arr.slice()
arr.slice(begin)
arr.slice(begin, end)

Tham số

Optional
Chỉ số bắt đầu chọn phần tử từ phần tử 0.
Nếu chỉ số này là số âm, được xem như tính ngược từ cuối của mảng.  chọn hai phần tử cuối cùng của mảng.
Nếu  là không xác định (undefined), bắt đầu từ chỉ số .

     Nếu begin lớn hơn độ dài của mảng, một mảng trống được trả về.

Optional
Chỉ số ngừng chọn phần tử.  chọn ra các phần tử có chỉ số trước chỉ số .
Ví dụ,  chọn phần thử thứ hai, thứ ba và thứ tư (ở các chỉ số 1, 2, và 3).
Chỉ số âm tính ngược từ cuối mảng về.  chọn các phần tử thứ ba cho đến phần tử sát cuối của mảng, không bao gồm phần từ cuối cùng ở chỉ số -1.
Nếu tham số  không được truyền vào,  chọn đến cuối mảng ()
Nếu  lớn hơn độ dài mảng, chỉ chọn đến cuối mảng ().
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector