Методы массивов

Parameter Values

Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will remove all elements, starting from the position set by the start-parameter.
array Optional. Specifies an array with the elements that will be inserted to the original array. If it’s only one element, it can be a string, and does not have to be an array.

Add/remove items

We already know methods that add and remove items from the beginning or the end:


  • – adds items to the end,
  • – extracts an item from the end,
  • – extracts an item from the beginning,
  • – adds items to the beginning.

Here are a few others.

How to delete an element from the array?

The arrays are objects, so we can try to use :

The element was removed, but the array still has 3 elements, we can see that .

That’s natural, because removes a value by the . It’s all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.

So, special methods should be used.

The arr.splice(start) method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.

The syntax is:

It starts from the position : removes elements and then inserts at their place. Returns the array of removed elements.

This method is easy to grasp by examples.

Let’s start with the deletion:

Easy, right? Starting from the index it removed element.

In the next example we remove 3 elements and replace them with the other two:

Here we can see that returns the array of removed elements:

The method is also able to insert the elements without any removals. For that we need to set to :

Negative indexes allowed

Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here:

The method arr.slice is much simpler than similar-looking .


The syntax is:

It returns a new array copying to it all items from index to (not including ). Both and can be negative, in that case position from array end is assumed.

It’s similar to a string method , but instead of substrings it makes subarrays.

For instance:

We can also call it without arguments: creates a copy of . That’s often used to obtain a copy for further transformations that should not affect the original array.

The method arr.concat creates a new array that includes values from other arrays and additional items.

The syntax is:

It accepts any number of arguments – either arrays or values.

The result is a new array containing items from , then , etc.

If an argument is an array, then all its elements are copied. Otherwise, the argument itself is copied.

For instance:

Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole:

…But if an array-like object has a special property, then it’s treated as an array by : its elements are added instead:

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

Массивы в JavaScript

Сперва нужно разобраться, как работают массивы JavaScript. Как и в других языках программирования, массивы используются для хранения нескольких единиц данных. Разница в том, что массивы JavaScript могут содержать несколько типов данных одновременно.

Чтобы работать с такими массивами, нам понадобятся JavaScript-методы: например, slice () & splice (). Создать массив можно так:

let arrayDefinition = [];   // Array declaration in JS

Теперь создадим другой массив с данными разного типа:

let array = ;

В JavaScript можно создавать массивы с разными типами данных: с числами, строками и логическими значениями.

Độ 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

Ví dụ

Tạo một mảng

Ví dụ sau tạo một mảng, , với chiều dài 0, sau đó gán giá trị cho và , thay đổi độ dài của mảng đến 100.

var msgArray = [];
msgArray  = "Hello";
msgArray  = 'thế giới';

if (msgArray.length === 100) {
  console.log ('Chiều dài là 100');
}

Tạo một mảng hai chiều


Sau đây tạo ra một bàn cờ như là một mảng hai chiều của chuỗi. Động thái đầu tiên được thực hiện bằng cách sao chép ‘p’ trong (6,4) đến (4,4). Các vị trí cũ (6,4) được làm trống.

Đây là kết quả:

R, N, B, Q, K, B, N, R
P, P, P, P, P, P, P, P
 ,,,,,,, 
 ,,,,,,, 
 ,,,,,,, 
 ,,,,,,, 
p, p, p, p, p, p, p, p
r, n, b, q, k, b, n, r

R, N, B, Q, K, B, N, R
P, P, P, P, P, P, P, P
 ,,,,,,, 
 ,,,,,,, 
 ,,,, P,,, 
 ,,,,,,, 
p, p, p, p,, p, p, p
r, n, b, q, k, b, n, r

說明

Array(「陣列」)是類似列表(list)的物件(Object),它們的原型(Prototype)擁有方法(methods)來執行遍歷和變異操作。JavaScript 陣列的長度(元素數量),以及其元素的類型都不是固定的。取決於工程師如何選擇使用陣列,可以隨時更改陣列的長度,也可不連續儲存資料, 所以並不保證這些資料是集中的。一般情況下,這些特性很方便使用;但若這些功能都不符合您的用途,您可能會想使用型別陣列(typed arrays)。

有些人認為即便會發生警告,仍然不應該使用關聯陣列,而應該使用 。您可參考輕量級 JavaScript 字典當中的範例。

存取陣列元素

JavaScript 陣列是 zero-indexed:陣列元素的索引值編排從 0 開始,而最後一個元素的索引值等同於陣列的 屬性減 1。

var arr = ;
console.log(arr);              // 紀錄出 'this is the first element'
console.log(arr);              // 記錄出 'this is the second element'
console.log(arr); // 記錄出 'this is the second element'

Array 元素同時也是物件的屬性,與 是一種屬性相同。但若要透過下面這種方式存取陣列元素,因為屬性名稱無效的關係,會發生語法錯誤:

console.log(arr.0); // 語法錯誤

會造成如此的原因沒有什麼特別的,在 JavaScript 當中無法用小數點的方式來參照一個名稱開頭為數字的屬性,而必須括號的表示方式來存取。舉例來說,若您有個物件的屬性名稱為「」,就只能用括號的方式來參照。

請看下列範例:

var years = ;
console.log(years.0);   // 語法錯誤
console.log(years);  // 程式正常
renderer.3d.setTexture(model, 'character.png');     // 語法錯誤
renderer.setTexture(model, 'character.png');  // 程式正常

注意:以這個  例子來說,必須用引號將 包起來。您也可以將 JavaScript 陣列的索引用引號包起來(例如使用 而不用 ),但這不是必要的。JavaScript 會透過隱含的 ,將 當中的 2 強制轉換為字串。由於這個原因, 與 會參照到 物件中的不同項目,下列程式範例結果可能回傳 :

console.log(years != years);

另一種類似的情況是,物件屬性剛好與保留字(!)相同的情況。這種情況下僅能透過括號表示方式當中的字串常值來存取:

var promise = {
  'var'  : 'text',
  'array': 
};

console.log(promise);

 與數值屬性的關係

JavaScript 陣列的 屬性和其數值屬性相關。許多陣列的方法被呼叫時會參考 屬性的值(例如 、、 等)。而有另一些方法則會去改變 屬性的值,如 、。

var fruits = [];
fruits.push('banana', 'apple', 'peach');

console.log(fruits.length); // 3

如果給陣列設定一個數值屬性,其值為有效但超過當下範圍的陣列 index,JavaScript 引擎會依照此數值更新陣列的 屬性:

fruits = 'mango';
console.log(fruits); // 'mango'
console.log(Object.keys(fruits));  // 
console.log(fruits.length); // 6

提高 屬性。

fruits.length = 10;
console.log(Object.keys(fruits)); // 
console.log(fruits.length); // 10

降低 屬性則會刪除陣列元素。

fruits.length = 2;
console.log(Object.keys(fruits)); // 
console.log(fruits.length); // 2

在 頁面裡有進一步解釋。

使用 match 回傳結果來建立陣列

// 比對一個字元 d,後面接著一或多個 b,再接著一個 d
// Remember matched b's and the following d
// 忽略大小寫

var myRe = /d(b+)(d)/i;
var myArray = myRe.exec('cdbBdbsbz');

這項比對結果的屬性與元素參考如下:

屬性/元素 說明 範例
唯讀屬性,代表 正規表示式用以比對的原始字串。 cdbBdbsbz
唯讀屬性,代表在字串中比對得到的索引,是以零為基礎(從0開始)。 1
一個唯獨元素以表示最後符合的字串 dbBd
Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited. : bB : d

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

Для их удаления нам надо задать параметр и число элементов, которые будут удалены:

array.splice(index, number of elements);

Тут — это начальная точка для удаления элементов. Элементы, которые имеют индекс ниже заданного не будут удалены:

array.splice(2); // Каждый элемент, начиная с 3го будет удалён

Если мы не указываем второй параметр, то будут удалены все элементы, начиная с заданного значения .

Во втором примере я задам вторым параметром число , что говорит о том, что элементы в массиве, начиная с числа будут удалены по одному, при каждом вызове метода :

array.splice(2, 1);

После 1-го вызова:

3 удалено, теперь строка “hello world” имеет index 2

После 2-го вызова:

В этот раз удаляется уже “hello world”

В общем, это будет продолжаться пока вообще не останется элементов под индексом 2.

示例

返回现有数组的一部分

var fruits = ;
var citrus = fruits.slice(1, 3);

// fruits contains 
// citrus contains 

译者注:citrus 柑橘类果实

使用

在下例中, 从 中创建了一个新数组。两个数组都包含了一个 对象的引用。当 的 属性改变为 ,则两个数组中的对应元素都会随之改变。

// 使用 slice 方法从 myCar 中创建一个 newCar。
var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = ;
var newCar = myCar.slice(0, 2);

// 输出 myCar、newCar 以及各自的 myHonda 对象引用的 color 属性。
console.log(' myCar = ' + JSON.stringify(myCar));
console.log('newCar = ' + JSON.stringify(newCar));
console.log(' myCar.color = ' + JSON.stringify(myCar.color));
console.log('newCar.color = ' + JSON.stringify(newCar.color));

// 改变 myHonda 对象的 color 属性.
myHonda.color = 'purple';
console.log('The new color of my Honda is ' + myHonda.color);

//输出 myCar、newCar 中各自的 myHonda 对象引用的 color 属性。
console.log(' myCar.color = ' + myCar.color);
console.log('newCar.color = ' + newCar.color);

上述代码输出:

 myCar = 
newCar = 
 myCar.color = red 
newCar.color = red
The new color of my Honda is purple
 myCar.color = purple
newCar.color = purple

С этим читают