1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
---
title: Array.prototype.includes()
slug: Web/JavaScript/Reference/Global_Objects/Array/includes
tags:
- Array
- JavaScript
- Method
- Prototype
- polyfill
- Довідка
- Масив
translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes
---
<div>{{JSRef}}</div>
<p><font face="Open Sans, Arial, sans-serif">Метод </font><code><strong>includes()</strong></code> з'ясовує, чи масив містить елемент із вказаним значенням, та вертає відповідно <code>true</code> або <code>false</code>.</p>
<p>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</p>
<div class="hidden">
<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p>
</div>
<h2 id="Синтаксис">Синтаксис</h2>
<pre class="syntaxbox">arr.includes(valueToFind[, fromIndex])</pre>
<h3 id="Параметри">Параметри</h3>
<dl>
<dt><em><code>valueToFind</code></em></dt>
<dd>Значення елемента, який слід знайти.</dd>
</dl>
<div class="blockIndicator note">
<p><strong>Примітка: </strong>При порівнянні рядків та літер, <code>includes()</code> <strong>чутливий до регістру</strong>.</p>
</div>
<dl>
<dt><em>fromIndex</em> {{optional_inline}}</dt>
<dd>Позиція у масиві, з якої потрібно починати пошук <code>valueToFind</code>; перша літера шукатиметься за індексом <code>fromIndex</code>, якщо <code>fromIndex</code> є позитивним значенням, або за індексом <code>array.length + fromIndex</code>, якщо <code>fromIndex</code> від'ємний (використовуючи {{interwiki("wikipedia", "Модуль_(математика)", "абсолютну величину")}} <code>fromIndex</code> як кількість літер з кінця масиву, де потрібно починати пошук). За замовчуванням дорівнює 0.</dd>
</dl>
<h3 id="Вертає">Вертає</h3>
<p>Значення {{jsxref("Boolean")}}, яке дорівнює <code>true</code>, якщо значення <code>valueToFind</code> знайдене у масиві (або у частині масиву, якщо заданий параметр <code>fromIndex</code>). Всі нульові значення вважаються рівними, незалежно від знаку (тому -0 вважатиметься рівним і 0, і +0), але <code>false</code> не вважається тим самим, що й 0.</p>
<div class="blockIndicator note">
<p><strong>Примітка:</strong> Технічно кажучи, <code>includes()</code> використовує алгоритм <code><a href="/uk/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality">sameValueZero</a></code> для визначення того, чи знайдено заданий елемент.</p>
</div>
<h2 id="Приклади">Приклади</h2>
<pre class="brush: js">[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
</pre>
<h3 id="fromIndex_більший_або_дорівнює_довжині_масиву"><em><code>fromIndex</code></em> більший або дорівнює довжині масиву</h3>
<p>Якщо <em><code>fromIndex</code></em> дорівнює або перевищує довжину масиву, пошук не здійснюється й завжди вертається <code>false</code>:</p>
<pre class="brush: js">var arr = ['a', 'b', 'c'];
arr.includes('c', 3); // вертає false
arr.includes('c', 100); // вертає false</pre>
<h3 id="Обчислений_індекс_менший_за_0">Обчислений індекс менший за 0</h3>
<p>Якщо значення <em><code>fromIndex</code></em> від'ємне, використовується обчислений індекс для визначення позиції, з якої починати пошук <em><code>valueToFind</code></em> у масиві. Якщо обчислений індекс менший або дорівнює <code>-1 * array.length</code>, пошук здійснюється у всьому масиві.</p>
<pre class="brush: js">// Довжина масиву дорівнює 3
// fromIndex дорівнює -100
// Обчислений індекс дорівнює 3 + (-100) = -97
var arr = ['a', 'b', 'c'];
arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false</pre>
<h3 id="Застосування_includes()_як_загального_метода">Застосування <code>includes()</code> як загального метода</h3>
<p>Реалізація метода <code>includes()</code> є зумисне узагальненою. Об'єкт, на який вказує <code>this</code>, не обов'язково повинен належати до класу <code>Array</code>, тож використання <code>includes()</code> можна поширити на інші масивоподібні об'єкти. В наведеному нижче прикладі його застосовано до об'єкта <code>{{jsxref("Functions/arguments", "arguments")}}</code>:</p>
<pre class="brush: js">(function() {
console.log([].includes.call(arguments, 'a')); // виводить true
console.log([].includes.call(arguments, 'd')); // виводить false
})('a','b','c');
</pre>
<div class="hidden">
<p>Будь ласка, не додавайте поліфіли у довідкові статті. Більше інформації дивіться у дискусії <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p>
</div>
<h2 id="Специфікації">Специфікації</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Специфікація</th>
<th scope="col">Статус</th>
<th scope="col">Коментар</th>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td>
<td>{{Spec2('ES7')}}</td>
<td>Початкова виознака.</td>
</tr>
</tbody>
</table>
<h2 id="Підтримка_веб-переглядачами">Підтримка веб-переглядачами</h2>
<div class="hidden">Таблиця сумісності на цій сторінці створена зі структурованих даних. Якщо ви хочете долучитися до розробки цих даних, пропонуйте нам свої pull request до репозиторію <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div>
<p>{{Compat("javascript.builtins.Array.includes")}}</p>
<h2 id="Див._також">Див. також</h2>
<ul>
<li>{{jsxref("TypedArray.prototype.includes()")}}</li>
<li>{{jsxref("String.prototype.includes()")}}</li>
<li>{{jsxref("Array.prototype.indexOf()")}}</li>
<li>{{jsxref("Array.prototype.find()")}}</li>
<li>{{jsxref("Array.prototype.findIndex()")}}</li>
</ul>
|