JS Deleting an Attribute in an Object
- 2021-08-16 22:52:50
- OfStack
The code is as follows
var obj={
name: 'zhagnsan',
age: 19
}
delete obj.name //true
typeof obj.name //undefined
Through the delete operator, you can delete the object attributes, and the return value is Boolean
Can I delete anything else
1. Variables
var name ='zs' // Declared variables
delete name //false
console.log(typeof name) //String
age = 19 // Undeclared variable
delete age //true
typeof age //undefined
this.val = 'fds' //window Variables under
delete this.val //true
console.log(typeof this.val) //undefined
The declared variables under windows can be deleted, but the undeclared variables cannot be deleted
2. Functions
var fn = function(){} // Declared functions
delete fn //false
console.log(typeof fn) //function
fn = function(){} // Undeclared function
delete fn //true
console.log(typeof fn) //undefined
3. Arrays
var arr = ['1','2','3'] /// Declared array
delete arr //false
console.log(typeof arr) //object
arr = ['1','2','3'] // Undeclared array
delete arr //true
console.log(typeof arr) //undefined
var arr = ['1','2','3'] // Declared array
delete arr[1] //true
console.log(arr) //['1','empty','3']
4. Objects
var person = {
height: 180,
long: 180,
weight: 180,
hobby: {
ball: 'good',
music: 'nice'
}
}
delete person ///false
console.log(typeof person) //object
var person = {
height: 180,
long: 180,
weight: 180,
hobby: {
ball: 'good',
music: 'nice'
}
}
delete person.hobby ///true
console.log(typeof person.hobby) //undefined
Declared objects cannot be deleted, and object properties in objects can be deleted