js中删除数组或对象

JavaScript013

js中删除数组或对象,第1张

在vue中使用

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

1、新建一个html页面,命名为test.html。

2、在test.html页面内,使用p标签创建三行文字。

3、在p标签的下面,创建一个button按钮,按钮名称为“清除网页内容”。

4、给button按钮绑定onclick点击事件,当按钮被点击时,执行delAll()函数。

5、在test.html页面内,使用function创建delAll函数。

6、在delAll函数内,获得当前页面body对象,使用innerHTML属性赋值为空的方法清除网页内容。

7、在浏览器中打开test.html页面,点击“清除网页内容”按钮,网页显示空白,内容被清除。