vue.delete()
删除对象属性
通过delete操作符, 可以实现对对象属性的删除操作, 返回值是布尔
例: var obj={name: 'zhagnsan',age: 19 }
delete obj.name //true
typeof obj.name //undefined
同样可用于函数,数组,变量,对象,但对象不能删除,只能做到删除对象属性
删除变量
例: 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
删除数组
以声明数组返回false,未声明返回true
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']
删除函数
var fn = function(){} //已声明的函数
delete fn //false
console.log(typeof fn) //function
fn = function(){} //未声明的函数
delete fn //true
console.log(typeof fn) //undefined
删除对象
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
var o = {a:1,b:2}console.log(o) // Object {a: 1, b: 2}
delete o['a'] // delete attr a
console.log(o) // Object {b: 2}
in判断的是对象的所有属性,包括对象实例及其原型的属性;而hasOwnProperty则是判断对象实例的是否具有某个属性。
示例代码:
<script type="text/javascript"> function Person(){ } Person.prototype.name = "allen" var person = new Person() console.log(person.hasOwnProperty("name"))//false console.log("name" in person)//true console.log(person.name)//"allen"person.name = "justforse" console.log(person.hasOwnProperty("name"))//true console.log("name" in person)//true console.log(person.name)//"justforuse"delete person.name console.log(person.hasOwnProperty("name"))//false console.log("name" in person)//true console.log(person.name)//"allen" </script>
以上代码执行的时候,name属性要么是从实例中获取的,要么是来源于原型,所以使用in 来访问 name属性始终返回true;而hasOwnProperty()只在属性存在与对象实例中时才返回true,当删除了实例中的name属性后,就恢复了原型中name属性的连接,所以返回allen。