JavaScript进阶 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

删除属性


delete 操作符是删除属性的唯一方法。把属性设置为undefined或者null不能真正的删除属性,它只是移除了属性和值的关联。

语法:delete 对象名.属性名;

示例:

创建一个cat对象,包含属性:name、sex和color。然后删除name属性,给sex赋值为undefined,给color赋值为null。在对各个属性进行判断是否存在。

var cat = {
    "name": "tom",
    "sex": "man",
    "color": "yellow"
}
delete cat.name;
cat.sex = undefined;
cat.color = null;
alert("name属性是否存在:" + cat.hasOwnProperty("name"));  //false
alert("sex属性是否存在:" + cat.hasOwnProperty("sex"));  //true
alert("color属性是否存在:" + cat.hasOwnProperty("color"));  //true

PS: hasOwnProperty函数是判断某个属性是否存在于某个对象当中。

创建一个对象,里面包含几个属性,利用delete删除其中一个属性,在通过hasOwnProperty()判断删除的属性是否存在。