JavaScript Видалення елементів з масиву. Javascript - елементів - видалити певний елемент масиву js Видалити значення з масиву js



Як видалити елемент з масиву за значенням? (20)

// відредагував спасибі MarcoCI за поради

Спробуй це:

Function wantDelete (item, arr) (for (var i = 0; i

сподіваюся, це допоможе вам

Чи є спосіб видалити елемент з масиву JavaScript?

З огляду на масив:

Var ary = [ "three", "seven", "eleven"];

Я хотів би зробити щось на кшталт:

RemoveItem ( "seven", ary);

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

Let commentsWithoutDeletedArray = commentsArray.filter ((comment) =>! (Comment.Id === commentId));

Ось версія, в якій використовується функція inArray jQuery:

Var index = $ .inArray (item, array); if (index! = -1) (array.splice (index, 1);)

Ви можете домогтися цього, використовуючи функцію Lodash _.remove.

var array = [ "three", "seven", "eleven"]; var evens = _.remove (array, function (e) (return e! == "seven";)); console.log (evens);

Const _ = require ( "lodash"); _.without (, 2); // ->

Дійсно, я не розумію, чому це неможливо вирішити за допомогою

Arr = arr.filter (value => value! == "seven");

Або, може бути, ви хочете використовувати vanilla JS

Arr = arr.filter (function (value) (return value! == "seven"));

Інший варіант:

If (! Array.prototype.removeArr) (Array.prototype.removeArr = function (arr) (if (! Array.isArray (arr)) arr =; // let "s be nice to people who put a non-array value here .. that could be me! var that = this; if (arr.length) (var i = 0; while (i -1) (that.splice (i, 1);) else i ++; )) Return that; ))

Це indexOf () всередині циклу знову, але в припущенні, що масив для видалення є малим щодо масиву, який потрібно очистити; кожне видалення скорочує цикл while.

Це дозволить вам зробити наступне:

Var ary = [ "three", "seven", "eleven"]; var aryWithoutSeven = ary.filter (function (value) (return value! = "seven")); console.log (aryWithoutSeven); // returns [ "three", "eleven"]

Це також було відзначено в цій темі десь ще: https: //.com/a/20827100/293492

Не використовуйте варіант з delete - він робить отвір в масиві, так як він не переіндексірует елементи після віддаленого елемента.

> Array.prototype.remove = function (v) (... delete this ...); > Var myarray = [ "3", "24", "55", "2"]; undefined> myarray.remove ( "55"); undefined> myarray [ "3", "24", "2"]

Один лайнер зробить це,

Var ary = [ "three", "seven", "eleven"]; // Remove item "seven" from array var filteredAry = ary.filter (function (e) (return e! == "seven")) // => [ "three", "eleven"] // In ECMA6 (arrow function syntax): var filteredAry = ary.filter (e => e! == "seven")

Це використовує функцію filter в JS. Він підтримується в IE9 і вище.

filter () викликає надану функцію зворотного виклику один раз для кожного елемента в масиві і створює новий масив з усіх значень, для яких зворотний виклик повертає значення, яке призводить до істинного. callback викликається тільки для індексів масиву, яким присвоєно значення; він не викликається для індексів, які були видалені або які ніколи не були присвоєні значенням. Елементи масиву, які не проходять тест на зворотний дзвінок, просто пропускаються і не включаються в новий масив.

Таким чином, в основному, це те ж саме, що і всі інші for (var key in ary) (...) рішень, за винятком того, що for in підтримується як IE6.

В принципі, фільтр - це метод зручності, який виглядає набагато краще (і є ланцюговим), на відміну від конструктора for in (AFAIK).

Перевірте це:

For (var i in array) (if (array [i] == "seven") (array.splice (i, 1); break;))

і в функції:

Function removeItem (array, item) (for (var i in array) (if (array [i] == item) (array.splice (i, 1); break;))) removeItem (array, "seven");

Видалення всіх співпадаючих елементів з масиву (а не тільки перший, як здається, самий загальний відповідь тут):

While ($ .inArray (item, array)> -1) (array.splice ($. InArray (item, array), 1);)

Я використовував jQuery для важкої роботи, але ви зрозуміли, чи хочете ви поїхати на рідну мову.

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

Var deleteMe = function (arr, me) (var i = arr.length; while (i--) if (arr [i] === me) arr.splice (i, 1);) var arr = [ "orange "," red "," black "," orange "," white "," orange "]; deleteMe (arr, "orange");

arr тепер [ "червоний", "чорний", "білий"]

Function cleanArrayOfSpecificTerms (array, unwantedTermsArray) ($ .each (unwantedTermsArray, function (index, value) (var index = array.indexOf (value); if (index> -1) (array.splice (index, 1);)) ); return array;)

Щоб використовувати, виконайте наступні дії:

Var notInclude = [ "Not", "No", "First", "Last", "Prior", "Next", "dogs", "cats"]; var splitTerms = [ "call", "log", "dogs", "cats", "topic", "change", "pricing"]; cleanArrayOfSpecificTerms (splitTerms, notInclude)

Я спробував використовувати метод функції з jbaron вище, але виявив, що мені потрібно зберегти вихідний масив без змін для використання пізніше і створити новий масив таким чином:

Var newArray = referenceArray;

Function newArrRemoveItem (array, item, newArray) (for (var i = 0; i< array.length; i++) { if(array[i]!=item){ newArray.push(array[i]); } } }

Потім я використовую його так:

Var vesselID = record.get ( "VesselID"); var otherVessels = new Array (); newArrRemoveItem (vesselArr, vesselID, otherVessels);

Тепер судноArr залишається неушкодженим, і кожен раз, коли я виконую наведений вище код, масив otherVessels включає в себе все, крім останнього елемента CAID.

indexOf - це варіант, але його реалізація в основному шукає весь масив для значення, тому час виконання зростає з розміром масиву. (Так що це в кожному браузері, я думаю, я тільки перевіряв Firefox).

У мене немає IE6 для перевірки, але я б назвав це безпечної ставкою, що ви можете перевірити по крайней мере мільйон елементів масиву в секунду таким чином практично на будь-який клієнтської машині. Якщо [розмір масиву] * [пошукові запити в секунду] може вирости більше мільйона, ви повинні розглянути іншу реалізацію.

В основному ви можете використовувати об'єкт для створення індексу для вашого масиву, наприклад:

Var index = ( "three": 0, "seven": 1, "eleven": 2);

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

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

// This function allows remove even array from array var removeFromArr = function (arr, elem) (var i, len = arr.length, new_arr =, sort_fn = function (a, b) (return a - b;); for ( i = 0; i< len; i += 1) { if (typeof elem === "object" && typeof arr[i] === "object") { if (arr[i].toString() === elem.toString()) { continue; } else { if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) { continue; } } } if (arr[i] !== elem) { new_arr.push(arr[i]); } } return new_arr; }

приклад використання

Var arr =, "abc", 1, "1", 1]; removeFromArr (arr, 1); // [ "2",, "abc", "1"] var arr = [, 2, "a",,]; removeFromArr (arr,); //]

Let arr =; console.log (arr); // result let index = arr.indexOf (30); if (index> -1) (arr.splice (index, 1);) console.log (arr); // result

Var index = array.indexOf ( "item"); if (index! = - 1) (array.splice (index, 1);)

зсув

Іспользуйте.shift для видалення першого елемента масиву.

наприклад:

Var array =; array.shift ();

масив призводить до:

наприклад:

Var array =; array.pop ();

масив призводить до:

Обидва методи повертають видалений елемент;

зрощування

Іспользуйте.splice () щоб видалити ряд елементів з масиву. .splice () приймає два параметри, початковий індекс і необов'язкове кількість елементів для видалення. Якщо другий параметр не.splice () видалить всі елементи з початкового індексу через кінець масиву.

наприклад:

Var array =; array.splice (1, 2);

залишає array, що містить:

Повернення array.splice () - це новий масив, що містить видалені елементи. У наведеному вище прикладі повернення буде наступним:

Таким чином, опускання другого параметра ефективно розбиває масив на два масиви з вихідним закінченням до зазначеного індексу:

Var array =; array.splice (2);

Залишає array містить і повертає.

видаляти

Використовуйте delete для видалення елемента з масиву без зміни довжини масиву:

Var array =; console.log (array.length); // 5 delete array; console.log (array); // console.log (array.length); // 5

Array.prototype.length

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

Array =; array.length = 2; console.log (array); //

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

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 https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

delete expression

Any variable defined with var is marked as non-configurable. In the following example, salary is non-configurable and can not be deleted. In non-strict mode, the delete operation will return false.

Function Employee () (delete salary; var salary;) Employee ();

Let "s see how the same code behaves in strict mode. Instead of returning false, the statement raises a SyntaxError.

"Use strict"; function Employee () (delete salary; // SyntaxError var salary;) // Similarly, any direct access to a function // with delete will raise a SyntaxError function DemoFunction () (// some code) delete DemoFunction; // SyntaxError

Examples

// Creates the property adminName on the global scope. adminName = "xyz"; // Creates the property empCount on the global scope. // Since we are using var, this is marked as non-configurable. The same is true of let and const. var empCount = 43; EmployeeDetails = (name: "xyz", age: 5, designation: "Developer"); // adminName is a property of the global scope. // It can be deleted since it is created without var, // and is therefore configurable. delete adminName; // returns true // On the contrary, empCount is not configurable // since var was used. delete empCount; // returns false // delete can be used to remove properties from objects. delete EmployeeDetails.name; // returns true // Even when the property does not exist, delete returns "true". delete EmployeeDetails.salary; // returns true // delete does not affect built-in static properties. delete Math.PI; // returns false // EmployeeDetails is a property of the global scope. // Since it was defined without "var", it is marked configurable. delete EmployeeDetails; // returns true function f () (var z = 44; // delete doesn "t affect local variable names delete z; // returns false)

delete and the prototype chain

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

Function Foo () (this.bar = 10;) Foo.prototype.bar = 42; var foo = new Foo (); // foo.bar is associated with the // own property. console.log (foo.bar); // 10 // Delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log (foo.bar); // 42 // Delete the property on the prototype. delete Foo.prototype.bar; // returns true // The "bar" property can no longer be // inherited from Foo since it has been // deleted. console.log (foo.bar); // undefined

Deleting array elements

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees is removed with delete.

Var trees = [ "redwood", "bay", "cedar", "oak", "maple"]; delete trees; if (3 in trees) (// this is not executed)

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees is assigned the value undefined, but the array element still exists:

Var trees = [ "redwood", "bay", "cedar", "oak", "maple"]; trees = undefined; if (3 in trees) (// this is executed)

If instead, you want to remove an array element by changing the contents of the array, use the splice method. In the following example, trees is removed from the array completely using splice:

Var trees = [ "redwood", "bay", "cedar", "oak", "maple"]; trees.splice (3,1); console.log (trees); // [ "redwood", "bay", "cedar", "maple"]

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "The delete Operator" in that specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of "The delete Operator" in that specification.
Standard
ECMAScript 1st Edition (ECMA-262)
The definition of "The delete Operator" in that specification.
Standard Initial definition. Implemented in JavaScript 1.2.

Browser compatibility

The compatibility table on 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

DesktopMobileServer
ChromeEdgeFirefoxInternet Explorer OperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
deleteChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

Legend

Full support Full support

Cross-browser notes

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position - not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

Сподобалася стаття? Поділіться з друзями!