JavaScript 值删除对象(Object)的属性——delete
原网址:https://blog.csdn.net/weixin_43553701/article/details/90757945
删除对象属性的方法
JS中如何删除对象中的某一属性
1 var obj={ 2 name: 'zhagnsan', 3 age: 19 4 } 5 delete obj.name //true 6 typeof obj.name //undefined
通过delete操作符,可以实现兑现属性的删除操作,返回值是布尔。
delete可以删除什么?
1. 变量
var name ='zs' //已声明的变量 delete name //false console.log(typeof name) //String age = 19 //未声明的变量 delete age //true typeof age //undefined this.val = 'fds' //window下的变量 delete this.val //true console.log(typeof this.val) //undefined
已声明的变量在windows下可删除,未声明的变量不可删除。
2.函数
1 var fn = function(){} //已声明的函数 2 delete fn //false 3 console.log(typeof fn) //function 4 5 fn = function(){} //未声明的函数 6 delete fn //true 7 console.log(typeof fn) //undefined
3.数组
var arr = ['1','2','3'] ///已声明的数组 delete arr //false console.log(typeof arr) //object arr = ['1','2','3'] //未声明的数组 delete arr //true console.log(typeof arr) //undefined var arr = ['1','2','3'] //已声明的数组 delete arr[1] //true console.log(arr) //['1','empty','3']
4. 对象
1 var person = { 2 height: 180, 3 long: 180, 4 weight: 180, 5 hobby: { 6 ball: 'good', 7 music: 'nice' 8 } 9 } 10 delete person ///false 11 console.log(typeof person) //object 12 13 var person = { 14 height: 180, 15 long: 180, 16 weight: 180, 17 hobby: { 18 ball: 'good', 19 music: 'nice' 20 } 21 } 22 delete person.hobby ///true 23 console.log(typeof person.hobby) //undefined
已声明的对象不可删除,对象中的对象属性可删除。
有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。