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
把for (var g = 0g <arr[i].c.lengthg++) {
改成
for (var g = arr[i].c.length-1g >=0g--) {
就正常了
原因就在于,如果从头开始循环,遇到连续两个需要删除的元素时,删掉第一个,下一个元素就自动顶上来代替已删除的元素位置,然后程序再一次循环时,就会跳过这个元素而去处理下下个元素,这样就会造成删除不全的情况了。
解决的办法就是从后面往前面删,就可以完美避免上面的问题。
var arr = new Array(0,1,2,3,4)// 删除从2开始的两个元素,位置从0开始
// 返回移除元素的数组
var reArr = arr.splice(2,2)