Array.prototype.join()

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:

示例

求数组中每个元素的平方根

下面的代码创建了一个新数组,值为原数组中对应数字的平方根。

var numbers = ;
var roots = numbers.map(Math.sqrt);
// roots的值为, numbers的值仍为

使用 map 重新格式化数组中的对象

以下代码使用一个包含对象的数组来重新创建一个格式化后的数组。

var kvArray = ;

var reformattedArray = kvArray.map(function(obj) { 
   var rObj = {};
   rObj = obj.value;
   return rObj;
});

// reformattedArray 数组为: , 

// kvArray 数组未被修改: 
// [{key: 1, value: 10}, 
//  {key: 2, value: 20}, 
//  {key: 3, value: 30}]

使用一个包含一个参数的函数来mapping(构建)一个数字数组

下面的代码表示了当函数需要一个参数时map的工作方式。当map循环遍历原始数组时,这个参数会自动被分配成数组中对应的每个元素。

var numbers = ;
var doubles = numbers.map(function(num) {
  return num * 2;
});

// doubles数组的值为: 
// numbers数组未被修改: 

一般的 方法

下面的例子演示如何在一个   上使用 map 方法获取字符串中每个字符所对应的 ASCII 码组成的数组:

var map = Array.prototype.map
var a = map.call("Hello World", function(x) { 
  return x.charCodeAt(0); 
})
// a的值为

下面代码展示了如何去遍历用 得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印:

var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
  return obj.value;
});

使用技巧案例

通常情况下, 方法中的 函数只需要接受一个参数,就是正在被遍历的数组元素本身。但这并不意味着 只给 传了一个参数。这个思维惯性可能会让我们犯一个很容易犯的错误。

考虑下例:

我们期望输出 , 而实际结果是 .

parseInt 经常被带着一个参数使用, 但是这里接受两个。第一个参数是一个表达式而第二个是callback function的基,  传递3个参数:

  • the element
  • the index
  • the array

第三个参数被parseInt忽视了, but not the second one, 但不是第二个。因此可能出现混淆。下面是迭代步骤的简明示例:

下面让我们来讨论解决方案:

一个map方法调用 parseInt 作为一个参数的等效输出运行如下:

(3) 

Ví dụ

Sử dụng

Ví dụ sau sẽ dùng để tìm vị trí của giá trị trong một mảng.

var array = ;
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

Tìm tất cả các lần xuất hiện của phần tử

var indices = [];
var array = ;
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// 

Xác định phần tử đã tồn tại trong mảng hay chưa và cập nhật lại mảng

function updateVegetablesCollection (veggies, veggie) {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie);
        console.log('New veggies collection is : ' + veggies);
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(veggie + ' already exists in the veggies collection.');
    }
}

var veggies = ;

updateVegetablesCollection(veggies, 'spinach'); 
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach'); 
// spinach already exists in the veggies collection.

Синтаксис

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

Параметри

Optional
Індекс на основі нуля, з якого починається копіювання.
Індекс може бути від’ємним, зазначаючи відступ з кінця послідовності.  копіює останні два елементи послідовності.
Якщо  не надано, починається з індексу .
Якщо  більший за довжину послідовності, повертається порожній масив.
Optional
Індекс на основі нуля до якого вібувається копіювання. копіює до, але не включаючи .
Наприклад,  копіює з другого по четвертий елемент (елементи за індексами 1, 2 та 3).
Індекс може бути від’ємним, зазначаючи відступ з кінця послідовності.  копіює з третього елемента по другий з кінця.
Якщо  пропущений, копіює до кінця послідовності ().
Якщо  більший за довжину послідовності, копіює до кінця послідовності ().

Оптимізація кросбраузерної поведінки

Хоча об’єкти середовища виконання (такі як об’єкти DOM) за специфікацією не зобов’язані відповідати поведінці Mozilla при перетворенні методом , і IE < 9 цього не робить, версії IE починаючи від 9-ї дозволяють це. Використання шима дозволяє  створити надійну кросбраузерну поведінку. Поки інші сучасні переглядачі підтримують цю можливість, як нині роблять IE, Mozilla, Chrome, Safari та Opera, розробники, які читають (підтримують для об’єктів DOM) slice-код, що покладається на цей шим, не будуть введені в оману семантикою; вони спокійно можуть покладатися на семантику, щоб реалізувати тепер вже де-факто стандартну поведінку. (Шим також виправляє роботу IE з другим аргументом , коли він явно заданий як /, чого більш ранні версії IE також не дозволяли, але всі сучасні переглядачі, в тому числі IE >= 9, зараз дозволяють.)

/**
 * Шим для "виправлення" слабкої підтримки IE (IE < 9) використання slice
 * на об'єктах середовища, таких як NamedNodeMap, NodeList та HTMLCollection
 * (технічно, оскільки об'єкти середовища були залежні від реалізації,
 * принаймні до ES2015, IE не мав потреби у цій функціональності.)
 * Також працює для рядків, виправляє IE < 9, дозволяючи явно задане значення
 * undefined другим аргументом (як у Firefox) та запобігає помилкам
 * при виклику на інших об'єктах DOM.
 */
(function () {
  'use strict';
  var _slice = Array.prototype.slice;

  try {
    // Не можна використовувати з елементами DOM у IE < 9
    _slice.call(document.documentElement);
  } catch (e) { // Не працює у IE < 9
    // Працюватиме для справжніх масивів, подібних до масивів об'єктів, 
    // NamedNodeMap (атрибутів, сутностей, нотацій),
    // NodeList (напр., getElementsByTagName), HTMLCollection (напр., childNodes),
    // і не схибить на інших об'єктах DOM (як на елементах DOM у IE < 9)
    Array.prototype.slice = function(begin, end) {
      // IE < 9 не любить undefined в якості аргументу end
      end = (typeof end !== 'undefined') ? end : this.length;

      // Для об'єктів Array використовуємо рідну функцію slice
      if (Object.prototype.toString.call(this) === ''){
        return _slice.call(this, begin, end); 
      }

      // Для подібних до масивів об'єктів робимо це самостійно.
      var i, cloned = [],
        size, len = this.length;

      // Обробляємо від'ємне значення "begin"
      var start = begin || 0;
      start = (start >= 0) ? start : Math.max(0, len + start);

      // Обробляємо від'ємне значення "end"
      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
      if (end < 0) {
        upTo = len + end;
      }

      // Очікуваний розмір нового масиву
      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;
    };
  }
}());

Tương thích trình duyệt

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

Introduction to JavaScript Array Concat

JavaScript Array Concat refers to combining of two or more arrays which in turn returns a new array. Combining different arrays does not result in the change of data in existing individual arrays. For concatenation, we use concat() method or Array.concat() function. Let us see the syntax and how it works.

How does Array Concatenation Works?

In Javascript, array is a list of elements may it be string, numbers, Boolean, etc. Concatenation is adding two arrays or more than 2 arrays. Similar to add, array1+ array2, concat() method works similarly in javascript. It appends the array elements at the end of the array to which the user wants to combine.

Web development, programming languages, Software testing & others

Syntax:

Syntax of concat() method is:

Arguments Value1, value2,… are the array or values which are to be combined to given array Returns a new array representing a joined array.

Above is the general way of concatenating the arrays, we also have some other methods to concatenate the arrays,

  1. Using spread operator E6 (keyboard shortcut)

Spread syntax is an ES6 standard which allows elements to be used as arguments, applicable while creating a new array, also known as a destructuring operator.

  1. Using Push

Using the push() method with spread operator. Let us have a look at some of the examples which will demonstrate the use of concat().

Popular Course in this category

JavaScript Training Program (39 Courses, 23 Projects)39 Online Courses | 23 Hands-on Projects | 225+ Hours | Verifiable Certificate of Completion | Lifetime Access 4.5 (4,284 ratings)

Course Price View Course

Related Courses
Angular JS Training Program (9 Courses, 7 Projects)Vue JS Training (1 Courses, 3 Project)Node JS Training Program (3 Courses, 7 Projects)Vue JS Training (1 Courses, 3 Project)

Examples of JavaScript Array Concat

Below are the examples of JavaScript Array Concat:

Code:

Output:

Here array1 and array2 both have 4 elements inside, on concatenation, a new array result is produced.

Example #2

In the case of more than 2 arrays.

Code:

Output:

Here, 4 arrays are combined and the output is as below, Since array4 is combined before array3, data in array4 is displayed first. There is no such thing as arrays should be combined in an order.

Example #3

We can also combine the elements directly to an array instead of declaring the second array and inserting the array elements.

Code:

Output:

Example #4

Code:

Output:

Output always depends on to which array we are combining which array, accordingly data gets inserted into a new array.

Example #5

We can even combine an array, some elements as below.

Code:

Output:

With concat(), arrays can also be cloned. We need to create an empty array and concat it with an already existing array.

Example #6

Code:

Output:

Conclusion

Let us now conclude this article as we have gone through what Javascript Array concatenation is, creating a new array by merging some or all the existing arrays as required, and demonstrated with various examples. I also investigated various other ways of concatenating arrays. Using concat() method, we have also seen cloning or copying the array elements to other arrays.

Recommended Articles

This is a guide to JavaScript Array Concat. Here we discuss how does Array Concatenation works and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –

  1. JavaScript String Format
  2. Javascript Nested Functions
  3. JavaScript Date Function
  4. JavaScript Array Filter

JavaScript Training Program (39 Courses, 23 Projects)

39 Online Courses

23 Hands-on Projects

225+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

Сумісність з веб-переглядачами

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

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

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()

Підтримка веб-переглядачів

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

Опис

Значенням властивості  є ціле додатне число, менше за 2 в степені 32 (232).

var namelistA = new Array(4294967296); //2 в степені 32 = 4294967296
var namelistC = new Array(-100) //від'ємне число

console.log(namelistA.length); //RangeError: Invalid array length
console.log(namelistC.length); //RangeError: Invalid array length

var namelistB = [];
namelistB.length = Math.pow(2,32)-1; //встановити довжину масиву меншу, ніж 2 в степені 32
console.log(namelistB.length); 

//4294967295

Ви можете присвоїти значення властивості , щоб скоротити масив. Коли ви розширюєте масив, змінюючи його довжину (властивість ), збільшується кількість фактичних елементів; наприклад, якщо ви присвоїли  3, коли елементів насправді 2, масив тепер містить 3 елементи, в результаті третій є неітерабельним порожнім елементом.

var arr = ;
console.log(arr);
// 

arr.length = 5; // встановити довжину 5, маючи 2 елементи.
console.log(arr);
// 

arr.forEach(element => console.log(element));
// 1
// 2

Таким чином, поле  не обов’язково вказує на кількість визначених значень у масиві. Дивіться також .

Атрибути поля
Доступний для запису так
Доступний для переліку ні
Доступний для налаштування ні
  • : Якщо цей атрибут встановлений у , значення цієї властивості не можна змінити.
  • : Якщо цей атрибут встановлений у , властивість ітерується під час виконання циклів for або for..in.
  • : Якщо цей атрибут встановлений у , будь-які спроби видалити властивість або змінити її атрибути (доступність для запису, переліку або налаштування) не спрацюють.

Приклади

.includes(2);      // true
.includes(4);      // false
.includes(3, 3);   // false
.includes(3, -1);  // true
.includes(NaN);  // true

більший або дорівнює довжині масиву

Якщо дорівнює або перевищує довжину масиву, пошук не здійснюється й завжди вертається :

var arr = ;

arr.includes('c', 3);    // вертає false
arr.includes('c', 100);  // вертає false

Обчислений індекс менший за 0

Якщо значення від’ємне, використовується обчислений індекс для визначення позиції, з якої починати пошук  у масиві. Якщо обчислений індекс менший або дорівнює , пошук здійснюється у всьому масиві.

// Довжина масиву дорівнює 3
// fromIndex дорівнює -100
// Обчислений індекс дорівнює 3 + (-100) = -97

var arr = ;

arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false

Застосування  як загального метода

Реалізація метода є зумисне узагальненою. Об’єкт, на який вказує , не обов’язково повинен належати до класу , тож використання можна поширити на інші масивоподібні об’єкти. В наведеному нижче прикладі його застосовано до об’єкта :

(function() {
  console.log([].includes.call(arguments, 'a'));  // виводить true
  console.log([].includes.call(arguments, 'd'));  // виводить false
})('a','b','c');

Будь ласка, не додавайте поліфіли у довідкові статті. Більше інформації дивіться у дискусії https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500

說明

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

Запасний варіант (поліфіл)

Цей метод був доданий у ECMAScript 2015, тож, можливо, поки наявний не у всякій реалізації JavaScript. Проте, ви можете використати наступний код для забезпечення запасного варіанту :

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Нехай O дорівнює ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Нехай len дорівнює ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. Якщо IsCallable(predicate) дорівнює false, викинути виняток TypeError.
      if (typeof predicate !== 'function') {
        throw new TypeError('предикат має бути функцією');
      }

      // 4. Якщо надано thisArg, нехай T дорівнює thisArg; інакше нехай T дорівнює undefined.
      var thisArg = arguments;

      // 5. Нехай k дорівнює 0.
      var k = 0;

      // 6. Повторювати, поки k < len
      while (k < len) {
        // a. Нехай Pk дорівнює ! ToString(k).
        // b. Нехай kValue дорівнює ? Get(O, Pk).
        // c. Нехай testResult дорівнює ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. Якщо testResult дорівнює true, повернути kValue.
        var kValue = o;
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Збільшити k на 1.
        k++;
      }

      // 7. Повернути undefined.
      return undefined;
    }
  });
}

Якщо вам потрібно забезпечити підтримку вкрай застарілих рушіїв JavaScript, в яких відсутня підтримка , було б краще взагалі не додавати методів до  через відсутність можливості заборонити їх перебір.

Підтримка веб-переглядачами

Таблиця сумісності на цій сторінці створена зі структурованих даних. Якщо ви хочете долучитися до розробки цих даних, пропонуйте нам свої pull request до репозиторію 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.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

Опис

Метод  виконує функцію  один раз для кожного елемента в масиві, аж поки не буде знайдено такий, для якого повертає . Щойно такий елемент знайдено, одразу ж повертає значення цього елемента. В іншому випадку,   повертає . Функція викликається для кожного індексу масиву з  по  і виконується для усіх елементів, не лише для тих, які мають присвоєні значення. Це означає, що цей метод може бути менш ефективним для розріджених масивів у порівнянні з методами, які обробляють лише ті, елементи, яким присвоєні значення.

Функція викликається з трьома аргументами: значення елемента, індекс елемента і об’єкт , перебір якого здійснюється.

Якщо параметр передано до , його буде використано як для кожного виклику . Якщо його не передано, тоді використовуватиметься .

Метод не змінює масив, для якого викликається.

Діапазон елементів, що їх має обробити , визначається ще до першого виклику функції . Тому  не обробляє елементи, додані до масиву після того, як почалося виконання . Якщо існуючий, ще не опрацьований елемент масиву, змінюється функцією , його значення, що передається до , буде значенням на той момент, коли  доходить до індексу цього елемента. Видалені елементи все одно опрацьовуються.

Mô tả

Phương thức  tạo ra 1 mảng mới bao gồm các phần tử trong đối tượng mà nó được gọi thực thi, và theo thứ tự lần lượt, với mỗi tham số truyền vào là các phần tử của tham số đó (nếu tham số truyền vào là 1 mảng) hoặc là chính tham số đó (nếu tham số truyền vào không  phải là 1 mảng). Phương thức này sẽ không thực thi 1 cách đệ quy cho các tham số là mảng lồng nhau.

Phương thức  không thay đổi  (mảng được gọi thực thi)  hay bất cứ mảng được truyền vào làm tham số mà thay vào đó nó sẽ trả về 1 bản sao tham chiếu (shallow copy) bao gồm các bản sao của cùng 1 phần tử được kết hợp từ các mảng ban đầu. Các phần từ của mảng ban đầu được sao chép vào mảng mới như sau: 

  • Đối với tham chiếu đối tượng (và không phải đối tượng thực tế): sao chép tham chiếu đối tượng vào mảng mới.  Cả mảng ban đầu và mảng mới đều tham chiếu tới cùng 1 đối tượng. Nghĩa là nếu đối tượng được tham chiếu tới bị thay đổi thì việc thay đổi đó sẽ ảnh hưởng trong cả mảng ban đầu và mảng mới. Điều này bao gồm các phần tử của các mảng làm tham số cũng đều là mảng. 

Chú ý: Việc ghép nối các mảng hay giá trị sẽ không «đụng chạm» tới các giá trị ban đầu. Hơn nữa, bất cứ thao tác nào trên mảng trả về (ngoại trừ các thao tác trên các phần từ là tham chiếu đối tượng) sẽ không ảnh hưởng tới các mảng ban đầu, và ngược lại.

Добавить комментарий

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

Adblock
detector