JavaScript中对象property的删除方法介绍
JavaScript中,可以使用delete操作符来删除对象中的property:
vart={a:42,b:26};
console.log(t);//Object{a=42,b=26}
deletet.a;
console.log(t);//Object{b=26}
这种property删除操作的局限性在于:delete操作符只能删除对象自身所有的property,无法删除其从prototype对象处继承而来的property。如果想删除prototype对象中的property,必须显式获取prototype对象后,在prototype对象中进行操作:
varo={x:1,y:2};
vara=Object.create(o);
a.z=3;
console.log(a);//Object{z=3,x=1,y=2}
deletea.x;//CanNOTdeleteinheritedproperty
console.log(a);//Object{z=3,x=1,y=2}
deletea.z;//Candeleteownproperty
console.log(a);//Object{x=1,y=2}
deletea.__proto__.x;
console.log(a);//Object{y=2}
如果删除了prototype对象中的property,那么所有从该prototype对象中继承的对象都会收到影响。
对于delete操作的返回值,JavaScript中遵循以下规则:
1.如果delete操作成功,返回true。
2.如果delete操作无任何效果(比如要删除的property并不存在),也返回true。
3.如果要delete的property,其configurable属性为false,那么在严格模式下会报TypeError错误,而在非严格模式下则返回false。
如果delete操作符所作用的是全局对象的property,那么在非严格模式下,代码中的全局对象可以省略:
this.c=42; deletec;//equaltodeletethis.c;
需要注意的是,在严格模式下,上述写法会抛SyntaxError错误。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下