--- title: Array.prototype.includes() slug: Web/JavaScript/Reference/Global_Objects/Array/includes tags: - JavaScript - Prototype - Reference - polyfill - Массив - метод translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes --- <div>{{JSRef}}</div> <p>Метод <code><strong>includes()</strong></code> определяет, содержит ли массив определённый элемент, возвращая в зависимости от этого <code>true</code> или <code>false</code>.</p> <div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> <h2 id="Синтаксис">Синтаксис</h2> <pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement[</var>, <var>fromIndex = 0]</var>) </pre> <h3 id="Параметры">Параметры</h3> <dl> <dt><code>searchElement</code></dt> <dd>Искомый элемент.</dd> <dt><code>fromIndex</code> {{optional_inline}}</dt> <dd>Позиция в массиве, с которой начинать поиск элемента <code>searchElement</code>. При отрицательных значениях поиск производится начиная с индекса <code>array.length + fromIndex</code> по возрастанию. Значение по умолчанию равно 0.</dd> </dl> <h3 id="Возвращаемое_значение">Возвращаемое значение</h3> <p>{{jsxref("Boolean")}}.</p> <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_больше_или_равен_длине_массива"><code>fromIndex</code> больше или равен длине массива</h3> <p>Если <code>fromIndex</code> больше или равен длине массива, то возвращается <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>Если <code>fromIndex</code> отрицательный, то вычисляется индекс, начиная с которого будет производиться поиск элемента <code>searchElement</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</pre> <h3 id="Использование_includes()_в_качестве_общих_метода">Использование <code>includes()</code> в качестве общих метода</h3> <p><code>includes()</code> специально сделан общим. Он не требует, чтобы <code>this</code> являлся массивом, так что он может быть применён к другим типам объектов (например, к массивоподобным объектам). Пример ниже показывает использование метода <code>includes()</code> на объекте <a href="/ru/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> <pre class="brush: js">(function() { console.log([].includes.call(arguments, 'a')); // true console.log([].includes.call(arguments, 'd')); // false })('a','b','c');</pre> <h2 id="Полифилл">Полифилл</h2> <pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.includes if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } // 1. Let O be ? ToObject(this value). var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If len is 0, return false. if (len === 0) { return false; } // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undefined, this step produces the value 0.) var n = fromIndex | 0; // 5. If n ≥ 0, then // a. Let k be n. // 6. Else n < 0, // a. Let k be len + n. // b. If k < 0, let k be 0. var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y) { return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); } // 7. Repeat, while k < len while (k < len) { // a. Let elementK be the result of ? Get(O, ! ToString(k)). // b. If SameValueZero(searchElement, elementK) is true, return true. if (sameValueZero(o[k], searchElement)) { return true; } // c. Increase k by 1. k++; } // 8. Return false return false; } }); } </pre> <p>Если требуется поддержка устаревших движков JavaScript, которые не поддерживают <code><a href="/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, наилучшим решением будет вообще не делать полифилл для методов <code>Array.prototype</code>, так как не получится сделать их неперечисляемыми.</p> <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('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> <td>{{Spec2('ES7')}}</td> <td>Изначальное определение.</td> </tr> <tr> <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> <td>{{Spec2('ESDraft')}}</td> <td></td> </tr> </tbody> </table> <h2 id="Поддержка_браузерами">Поддержка браузерами</h2> <div> <p>{{Compat("javascript.builtins.Array.includes")}}</p> </div> <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>