標籤:
Key word delete.
1. Delete global object.
x = 42; // creates the property x on the global objectvar y = 43; // creates the property y on the global object, and marks it as non-configurablemyobj = { h: 4, k: 5};// x is a property of the global object and can be deleteddelete x; // returns true// y is not configurable, so it cannot be deleted delete y; // returns false // delete doesn‘t affect certain predefined propertiesdelete Math.PI; // returns false // user-defined properties can be deleteddelete myobj.h; // returns true // myobj is a property of the global object, not a variable,// so it can be deleteddelete myobj; // returns truefunction f() { var z = 44; // delete doesn‘t affect local variable names delete z; // returns false}
2. Function
function Foo(){}Foo.prototype.bar = 42;var foo = new Foo();// returns true, but with no effect, // since bar is an inherited propertydelete foo.bar; // logs 42, property still inheritedconsole.log(foo.bar);// deletes property on prototypedelete Foo.prototype.bar; // logs "undefined", property no longer inheritedconsole.log(foo.bar);
3. Array
var trees = ["redwood","bay","cedar","oak","maple"];delete trees[3];if (3 in trees) { // this does not get executed}var trees = ["redwood","bay","cedar","oak","maple"];trees[3] = undefined;if (3 in trees) { // this gets executed}
delete in javascript