我对javascript相当陌生。我注意到,显然在“使用严格”模式下操作时,您无法删除对象。我不是删除东西的忠实拥护者(因为理论上,范围无论如何都应该处理这个问题),但我想知道删除此功能的动机是什么?
问问题
46561 次
2 回答
87
delete
在严格模式下仍然允许该语句,但它的某些特定用途是错误的。它只允许用于对象属性,而不是简单的名称,并且只允许用于可以删除的对象属性。
因此
var a = {x: 0};
delete a.x;
很好,但是
delete Object.prototype;
不是,也不是
delete a;
(后者实际上是语法级别的错误,而尝试删除不可删除的属性是运行时错误。)
于 2013-05-20T15:13:12.000 回答
6
[delete] 用例子详细解释
// The delete statement is still allowed in strict mode, but some particular uses of it are erroneous. It's only allowed for object properties, not simple names, and only for object properties that can be deleted.
// "use strict";
// creates the property adminName on the global scope
adminName = "xyz";
// creates the property empCount on the global scope
// Since we are using var, this is marked as non-configurable. The same is true of let and const.
var empCount = 43;
EmployeeDetails = {
name: "xyz",
age: 5,
designation: "Developer"
};
// adminName is a property of the global scope.
// It can be deleted since it is created without var.
// Therefore, it is configurable.
console.log("delete adminName =", delete adminName); // returns true
// On the contrary, empCount is not configurable,
// since var was used.
console.log("delete empCount =", delete empCount); // returns false
// delete can be used to remove properties from objects
console.log("delete EmployeeDetails.name =", delete EmployeeDetails.name); // returns true
// Even when the property does not exists, it returns "true"
console.log("delete EmployeeDetails.salary =", delete EmployeeDetails.salary); // returns true
// delete does not affect built-in static properties
console.log("delete Math.PI =", delete Math.PI); // returns false
// EmployeeDetails is a property of the global scope.
// Since it defined without "var", it is marked configurable
console.log("delete EmployeeDetails =", delete EmployeeDetails); // returns true
x = 1;
var y = 2;
function f() {
var z = 44;
console.log("delete x =", delete x); // returns true
console.log("delete y =", delete y); // returns false
// delete doesn't affect local variable names
console.log("delete z =", delete z); // returns false
}
f.call();
于 2018-02-07T07:45:28.883 回答