Javascript удалить массив объектов

delete operator

The delete operator removes a property from an object. If the property’s value is an object and there are no more references to the object, the object held by that property is eventually released automatically.

Try it

Syntax

delete object.property delete object[property] 

Note: The syntax allows a wider range of expressions following the delete operator, but only the above forms lead to meaningful behaviors.

Parameters

The name of an object, or an expression evaluating to an object.

Return value

true for all cases except when the property is an own non-configurable property, in which case false is returned in non-strict mode.

Exceptions

Thrown in strict mode if the property is an own non-configurable property.

Description

The delete operator has the same precedence as other unary operators like typeof . Therefore, it accepts any expression formed by higher-precedence operators. However, the following forms lead to early syntax errors in strict mode:

delete identifier; delete object.#privateProperty; 

Because classes are automatically in strict mode, and private properties can only be legally referenced in class bodies, this means private properties can never be deleted. While delete identifier may work if identifier refers to a configurable property of the global object, you should avoid this form and prefix it with globalThis instead.

Читайте также:  Whatsapp for java samsung phone

While other expressions are accepted, they don’t lead to meaningful behaviors:

delete console.log(1); // Logs 1, returns true, but nothing deleted 

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned. Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. See the memory management page for more details.

It is important to consider the following scenarios:

  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true .
  • delete only has an effect on own properties. If a property with the same name exists on the object’s prototype chain, then after deletion, the object will use the property from the prototype chain.
  • Non-configurable properties cannot be removed. This includes properties of built-in objects like Math , Array , Object and properties that are created as non-configurable with methods like Object.defineProperty() .
  • Deleting variables, including function parameters, never works. delete variable will throw a SyntaxError in strict mode, and will have no effect in non-strict mode.
    • Any variable declared with var cannot be deleted from the global scope or from a function’s scope, because while they may be attached to the global object, they are not configurable.
    • Any variable declared with let or const cannot be deleted from the scope within which they were defined, because they are not attached to an object.

    Examples

    Using delete

    Note: The following example uses non-strict-mode only features, like implicitly creating global variables and deleting identifiers, which are forbidden in strict mode.

    // Creates the property empCount on the global scope. // Since we are using var, this is marked as non-configurable. var empCount = 43; // Creates the property EmployeeDetails on the global scope. // Since it was defined without "var", it is marked configurable. EmployeeDetails =  name: "xyz", age: 5, designation: "Developer", >; // 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 // EmployeeDetails is a property of the global scope. delete EmployeeDetails; // returns true // On the contrary, empCount is not configurable // since var was used. delete empCount; // returns false // delete also does not affect built-in static properties // that are non-configurable. delete Math.PI; // returns false 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; const 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[3] is removed with delete .

    const trees = ["redwood", "bay", "cedar", "oak", "maple"]; delete trees[3]; console.log(3 in trees); // false 

    This creates a sparse array with an empty slot. 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[3] is assigned the value undefined , but the array element still exists:

    const trees = ["redwood", "bay", "cedar", "oak", "maple"]; trees[3] = undefined; console.log(3 in trees); // true 

    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[3] is removed from the array completely using splice() :

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

    Deleting non-configurable properties

    When a property is marked as non-configurable, delete won’t have any effect, and will return false . In strict mode, this will raise a TypeError .

    const Employee = >; Object.defineProperty(Employee, "name",  configurable: false >); console.log(delete Employee.name); // returns false 

    var creates non-configurable properties that cannot be deleted with the delete operator:

    // Since "nameOther" is added using with the // var keyword, it is marked as non-configurable var nameOther = "XYZ"; // We can access this global property using: Object.getOwnPropertyDescriptor(globalThis, "nameOther"); // // value: "XYZ", // writable: true, // enumerable: true, // configurable: false // > delete globalThis.nameOther; // return false 

    In strict mode, this would raise an exception.

    Deleting global properties

    If a global property is configurable (for example, via direct property assignment), it can be deleted, and subsequent references to them as global variables will produce a ReferenceError .

    .globalVar = 1; console.log(globalVar); // 1 // In non-strict mode, you can use `delete globalVar` as well delete globalThis.globalVar; console.log(globalVar); // ReferenceError: globalVar is not defined 

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    See also

    Found a content problem with this page?

    This page was last modified on Jun 7, 2023 by MDN contributors.

    Your blueprint for a better internet.

    Источник

    Удалить объект из массива в JavaScript

    Удалить объект из массива в JavaScript

    1. Используйте метод splice() для удаления объекта из массива в JavaScript
    2. Использование метода slice() для удаления объекта из массива в JavaScript
    3. Используйте метод filter() для удаления объекта из массива

    В этой статье мы узнаем, как удалить объект из массива JavaScript. В статье будут представлены и реализованы такие методы, как splice() , slice() и filter() .

    Используйте метод splice() для удаления объекта из массива в JavaScript

    Метод splice() может быть лучшим методом, который мы можем использовать для удаления объекта из массива. Он изменяет содержимое массива, удаляя или заменяя существующие элементы или добавляя новые элементы на место. Синтаксис метода splice() показан ниже.

    Array.splice(index, count, items1, . , itemX) 

    Опция index относится к целому числу, которое указывает, в какую позицию добавлять / удалять элементы. Мы также можем использовать отрицательные значения, чтобы указать позицию от конца массива. Опция count является необязательной и указывает количество элементов, которые нужно удалить. Опция items1, . itemX также является необязательной и может использоваться для добавления новых элементов в массив.

    Сначала мы объявляем переменную массива с именем myArray , которая содержит три объекта в массиве. Затем во второй строке мы используем метод splice() к массиву. Мы также указываем 0 и 1 в качестве аргументов. Затем записываем массив в консоль.

    Изначально массив содержит три объекта. Значение 0 в методе splice() указывает первый индекс массива, то есть первый объект. Это означает, что мы начнем удаление с первого индекса. Следующее значение, 1 в методе, указывает, что метод удалит один элемент из начальной точки. Таким образом, в приведенном ниже примере будет удален первый объект в массиве.

    Отметим, что метод splice() модифицирует массив; таким образом, мы можем использовать метод slice() для удаления желаемого объекта из массива без изменения исходного массива.

    var myArray = [:1, name:'John'>,:2, name:'Rick'>,:3, name:'Anna'>]; myArray.splice(0,1) console.log(myArray) 

    Использование метода slice() для удаления объекта из массива в JavaScript

    Метод slice() возвращает измененную копию части массива, выбранной от начала до конца, но конечный индекс, переданный в метод, не будет включен. Синтаксис метода slice() приведен ниже.

    Array.slice(startIndex, endIndex) 

    Здесь startIndex — это индекс, отсчитываемый от нуля, с которого мы начинаем извлечение. Может использоваться отрицательный индекс, который указывает смещение от конца последовательности. Например, slice(-3) извлекает последние три элемента в последовательности. Если startIndex не определен, функция slice() запускается с индекса 0 , тогда как если startIndex больше диапазона индексов массива, возвращается пустой массив.

    Параметр endIndex также является индексом с отсчетом от нуля, перед которым завершается извлечение. Метод slice() извлекает до endIndex , но включает сам endIndex . Если опция endIndex исключена, функция slice() выполняет извлечение до конца последовательности, то есть до array.length . Если endIndex больше длины последовательности, функция slice() также выполняет извлечение до конца последовательности.

    Метод slice(1,3) в примере ниже извлечет элементы из второго индекса в четвертый. Поскольку в массиве нет четвертого индекса, он будет извлекать элементы до конца последовательности.

    var myArray = [:1, name:'Morty'>,:2, name:'Rick'>,:3, name:'Anna'>]; var newArray = myArray.slice(1, 3); console.log(newArray) 

    Используйте метод filter() для удаления объекта из массива

    Метод filter() создает новый массив с элементами, которые проходят проверку, предоставленную функцией. Это означает, что он вернет новый массив объектов. Если ни один элемент не прошел проверку, функция вернет пустой массив. Мы будем использовать стрелочную функцию, чтобы продемонстрировать метод filter() .

    Метод filter() использует терминологию, называемую функцией обратного вызова, которая выглядит как

    var newArray = myArray.filter( (element, index, array) =>  . Items passing this condition will be added to the new array. >) 

    Метод принимает три аргумента. Опция element — это текущий обрабатываемый элемент в массиве. index является необязательным и указывает индекс текущего обрабатываемого элемента в массиве. Наконец, опция array — это вызываемый и необязательный фильтр массива.

    Сначала создайте массив с объектами, как это сделано в описанных выше методах. Затем вызовите функцию filter() с переменной массива. Укажите item в качестве аргумента стрелочной функции и верните элементы массива с выражением item.id ! == 1 . Сохраните новый массив в переменной newArray и зарегистрируйте его в консоли.

    Пример ниже возвращает только элемент массива, чей id не равен значению 1 . Таким образом, он возвращает второй и третий элемент массива.

    var myArray = [:1, name:'Morty'>,:2, name:'Rick'>,:3, name:'Anna'>]; var newArray = myArray.filter((item) => item.id !== 1); console.log(newArray); 

    Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

    Сопутствующая статья — JavaScript Array

    Copyright © 2023. All right reserved

    Источник

Оцените статью