js delete a certain field in the object

 // 以下方法不改变原来对象
      let item = {
        name:'张三',
        age:'18',
        gender:'男'
      };
      console.log(item) // {age: "18",gender: "男",name: "张三"}


     let { age,...params } = item;
      console.log(item) // {age: "18",gender: "男",name: "张三"}
      console.log(typeof params.age) // undefined
      console.log(params) // {gender: "男",name: "张三"}

      // 以下方法会直接改变对象
      let item1 = {
        name:'张三',
        age:'18',
        gender:'男'
      };
      console.log(item1) // {age: "18",gender: "男",name: "张三"}
      delete item1.name;
      console.log(typeof item1.name) // undefined
      console.log(item1) // // {age: "18",gender: "男"}

Contrary to common belief, deleteoperators are related to direct release of memory 无关. Memory management is done indirectly by breaking references, see 内存管理.

deleteThe operator removes the specified attribute from an object. It returns true when it is successfully deleted, otherwise it returns false.

However, the following situations need to be considered:

If the property you are trying to delete does not exist, it deletewill not have any effect, but it will still return. true
If there is a property on the prototype chain of the object with the same name as the property to be deleted, then after deleting the property, the object will use the one on the prototype chain property (that is, deletethe operation will only work on their own property)
any use of varproperty declaration can not be removed from the scope or function of global scope.
In this case, the deleteoperation cannot delete any function in the global scope (regardless of whether the function comes from a function declaration or function expression).
In addition to the function in the global scope, the function cannot be deleted. The function in the object ( object) can be used deleteOperation deleted.
Any attribute declared with letor conscannot be deleted from the scope in which it is declared.
The non-settable ( Non-configurable) attributes cannot be removed. This means that, like Math, Array, Objectproperties, and use the built-in object Object.defineProperty()methods to property is not set can not be deleted.
The following code block gives a simple example:

var Employee = {
  age: 28,
  name: 'abc',
  designation: 'developer'
}

console.log(delete Employee.name);   // returns true
console.log(delete Employee.age);    // returns true

// 当试着删除一个不存在的属性时
// 同样会返回true
console.log(delete Employee.salary); // returns true

Non-configurable attributes

When an attribute is set as not settable, the deleteoperation will have no effect and will return false. A syntax error ( SyntaxError) will be thrown in strict mode .

var Employee = {};
Object.defineProperty(Employee, 'name', {configurable: false});

console.log(delete Employee.name);  // returns false

var, letAnd the constproperty is not set can not be created deleteoperating deleted.

var nameOther = 'XYZ';

// 通过以下方法获取全局属性:
Object.getOwnPropertyDescriptor(window, 'nameOther');

// 输出: Object {value: "XYZ",
//                  writable: true,
//                  enumerable: true,
//                  configurable: false}

// 因为“nameOther”使用var关键词添加,
// 它被设置为不可设置(non-configurable)
delete nameOther;   // return false

In strict mode, such an operation will throw an exception.

Comparison of strict mode and non-strict mode

In strict mode, if you use the delete operation on a direct reference to a variable, a function parameter, or a function name, a SyntaxError will be thrown. Therefore, to avoid syntax errors in strict mode, the delete operator must be used in the form of delete object.property or delete object['property'].

Object.defineProperty(globalThis, 'variable1', { value: 10, configurable: true, });
Object.defineProperty(globalThis, 'variable2', { value: 10, configurable: false, });

console.log(delete variable1); // true

// SyntaxError in strict mode.
console.log(delete variable2); // false
function func(param) {
  // SyntaxError in strict mode.
  console.log(delete param); // false
}

// SyntaxError in strict mode.
console.log(delete func); // false

Any variable declared with var will be marked as unsettable. In the example below, salary is not settable and cannot be deleted. In non-strict mode, the delete operation below will return false.

function Employee() {
  delete salary;
  var salary;
}

Employee();

Let's see how the same code behaves in strict mode. Will throw a SyntaxError instead of returning false.

"use strict";

function Employee() {
  delete salary;  // SyntaxError
  var salary;
}

// 相似的,任何对任何函数
// 直接使用delete操作将会抛出语法错误。

function DemoFunction() {
  //some code
}

delete DemoFunction; // SyntaxError

Example

// 在全局作用域创建 adminName 属性
adminName = 'xyz';

// 在全局作用域创建 empCount 属性
// 因为我们使用了 var,它会标记为不可配置。同样 let 或 const 也是不可配置的。
var empCount = 43;

EmployeeDetails = {
  name: 'xyz',
  age: 5,
  designation: 'Developer'
};

// adminName 是全局作用域的一个属性。
// 因为它不是用 var 创建的,所在可以删除。
// 因此,它是可配置的。
delete adminName;       // 返回 true

// 相反,empCount 是不可配置的,
// 因为创建它时使用了 var。
delete empCount;       // 返回 false

// delete 可用于删除对象的属性
delete EmployeeDetails.name; // 返回 true

// 甚至属性不存在,它也会返回 "true"
delete EmployeeDetails.salary; // 返回 true

// delete 对内建静态属性不起作用
delete Math.PI; // 返回 false

// EmployeeDetails 是全局作用域的一个属性。
// 因为定义它的时候没有使用 "var",它被标记为可配置。
delete EmployeeDetails;   // 返回 true

function f() {
  var z = 44;

  // delete 对局部变量名不起作用
  delete z;     // 返回 false
}

delete and prototype chain

In the following example, we delete an object's own properties, and properties with the same name on the prototype chain are available:

function Foo() {
  this.bar = 10;
}

Foo.prototype.bar = 42;

var foo = new Foo();

// 返回 true,因为删除的是 foo 对象的自身属性
delete foo.bar;

// foo.bar 仍然可用,因为它在原型链上可用。
console.log(foo.bar);   //42

// 从原型上删除属性
delete Foo.prototype.bar; //true

// 由于已删除“ bar”属性,因此不能再从Foo继承它。
console.log(foo.bar);    //undefined

Delete array elements

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

When using the delete operator to delete an array element, the deleted element no longer belongs to the array. The following example uses delete to delete trees[3].

var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
   // 这里不会执行
}

If you want an array element to continue to exist but its value is undefined, you can assign undefined to this element instead of delete. In the following example, trees[3] is assigned the value undefined, but the element still exists.

var trees = ["redwood","bay","cedar","oak","maple"];
trees[3] = undefined;
if (3 in trees) {
   // 这里会被执行
}

If 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 by using splice().

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

Guess you like

Origin blog.csdn.net/weixin_43764814/article/details/112425203