delete

  • Revision slug: JavaScript/Reference/Operators/delete
  • Revision title: delete
  • Revision id: 340481
  • Created:
  • Creator: nurbek.ab
  • Is current revision? Нет
  • комментировать

Revision Content

Аннотация

Оператор delete удаляет свойство из объекта.

Оператор
Реализован в: JavaScript 1.2
Версия ECMAScript: ECMA-262 1-ый выпуск

Синтаксис

delete выражение

где выражение должно расцениваться (javascript-интерпретатором) как ссылка на свойство, например:

delete object.property
delete object['property']
delete object[index]
delete property // удаляет свойства глобального объекта, или, 
                // используя инструкцию with, свойства объекта, на который ссылается инструкция

Если выражение не расценивается (javascript-интерпретатором) как свойство (объекта), delete ничего не делает.

Параметры

object
Имя объекта или выражение, результатом вычисления которого является объект.
property
The property to delete.
index
An integer representing the array index to delete.

Returns

Returns false only if the property exists on the object itself, regardless of its prototypes, and cannot be deleted. It returns true in all other cases.

Description

If the delete operator succeeds, it removes the property from the object entirely. However, if a property with the same name exists on the object's prototype chain, the object will inherit that property from the prototype.

delete is only effective on an object's properties. It has no effect on variable or function names.
While sometimes mischaracterized as global variables, assignments that don't specify an object (e.g. x = 5) are actually property assignments on the global object.

delete can't remove certain properties of predefined objects (like Object, Array, Math etc). These are marked in the ECMA 262 specification as DontDelete.

x = 42;         // creates the property x on the global object
var y = 43;     // declares a new variable, y
myobj = {};
myobj.h = 4;    // creates property h on myobj
myobj.k = 5;    // creates property k on myobj

delete x;       // returns true  (x is a property of the global object and can be deleted)
delete y;       // returns false (delete doesn't affect variable names)
delete Math.PI; // returns false (delete doesn't affect certain predefined properties)
delete myobj.h; // returns true  (user-defined properties can be deleted)

with(myobj) { 
    delete k;   // returns true  (equivalent to delete myobj.k)
} 

delete myobj;   // returns true  (myobj is a property of the global object, not a variable, so it can be deleted)

If the object inherits a property from a prototype, and doesn't have the property itself, the property can't be deleted by referencing the object. You can, however, delete it directly on the prototype.

function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();
delete foo.bar;           // returns true, but with no effect, since bar is an inherited property
alert(foo.bar);           // alerts 42, property still inherited
delete Foo.prototype.bar; // deletes property on prototype
alert(foo.bar);           // alerts "undefined", property no longer inherited

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a{{ mediawiki.external(3) }}, a{{ mediawiki.external(4) }} is still a{{ mediawiki.external(4) }} and a{{ mediawiki.external(3) }} is undefined. This holds even if you delete the last element of the array (delete a{{ mediawiki.external('a.length-1') }}).

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees{{ mediawiki.external(3) }} is removed with delete.

var trees = ["redwood","bay","cedar","oak","maple"];

delete trees[3];
if (3 in trees) {
    // this does not get executed
}

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees{{ mediawiki.external(3) }} is assigned the value undefined, but the array element still exists:

var trees = ["redwood","bay","cedar","oak","maple"];
trees[3]=undefined;
if (3 in trees) {
    // this gets executed
}

Cross-browser issues

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

External links

Revision Source

<h2 id="Summary" name="Summary">Аннотация</h2>
<p>Оператор <code>delete</code> удаляет свойство из объекта.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2" scope="row">Оператор</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Реализован в:</td>
      <td>JavaScript 1.2</td>
    </tr>
    <tr>
      <td>Версия ECMAScript:</td>
      <td>ECMA-262 1-ый выпуск</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax" name="Syntax">Синтаксис</h2>
<p><code>delete <em>выражение</em></code></p>
<p>где <em>выражение</em> должно расцениваться (javascript-интерпретатором) как ссылка на свойство, например:</p>
<pre class="syntaxbox">
delete <em>object.property</em>
delete <em>object</em>['<em>property</em>']
delete <em>object</em>[<em>index</em>]
delete <em>property</em> // удаляет свойства глобального объекта, или, 
                // используя инструкцию <em>with</em>, свойства объекта, на который ссылается инструкция
</pre>
<p>Если <em>выражение</em> не расценивается (javascript-интерпретатором) как свойство (объекта), <code>delete</code> ничего не делает.</p>
<h3 id="Parameters" name="Parameters">Параметры</h3>
<dl>
  <dt>
    <code>object</code></dt>
  <dd>
    Имя объекта или выражение, результатом вычисления которого является объект.</dd>
  <dt>
    <code>property</code></dt>
  <dd>
    The property to delete.</dd>
  <dt>
    <code>index</code></dt>
  <dd>
    An integer representing the array index to delete.</dd>
</dl>
<h3 id="Returns" name="Returns">Returns</h3>
<p>Returns false only if the property exists on the object itself, regardless of its prototypes, and cannot be deleted. It returns true in all other cases.</p>
<h2 id="Description" name="Description">Description</h2>
<p>If the <code>delete</code> operator succeeds, it removes the property from the object entirely. However, if a property with the same name exists on the object's prototype chain, the object will inherit that property from the prototype.</p>
<p><code>delete</code> is only effective on an object's properties. It has no effect on variable or function names.<br />
  While sometimes mischaracterized as global variables, assignments that don't specify an object (e.g. <code>x = 5</code>) are actually property assignments on the global object.</p>
<p><code>delete</code> can't remove certain properties of predefined objects (like Object, Array, Math etc). These are marked in the ECMA 262 specification as <em>DontDelete.</em></p>
<pre class="brush: js">
x = 42;         // creates the property x on the global object
var y = 43;     // declares a new variable, y
myobj = {};
myobj.h = 4;    // creates property h on myobj
myobj.k = 5;    // creates property k on myobj

delete x;       // returns true  (x is a property of the global object and can be deleted)
delete y;       // returns false (delete doesn't affect variable names)
delete Math.PI; // returns false (delete doesn't affect certain predefined properties)
delete myobj.h; // returns true  (user-defined properties can be deleted)

with(myobj) { 
    delete k;   // returns true  (equivalent to delete myobj.k)
} 

delete myobj;   // returns true  (myobj is a property of the global object, not a variable, so it can be deleted)</pre>
<p>If the object inherits a property from a prototype, and doesn't have the property itself, the property can't be deleted by referencing the object. You can, however, delete it directly on the prototype.</p>
<pre class="brush: js">
function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();
delete foo.bar;           // returns true, but with no effect, since bar is an inherited property
alert(foo.bar);           // alerts 42, property still inherited
delete Foo.prototype.bar; // deletes property on prototype
alert(foo.bar);           // alerts "undefined", property no longer inherited</pre>
<h3 id="Deleting_array_elements" name="Deleting_array_elements">Deleting array elements</h3>
<p>When you delete an array element, the array length is not affected. For example, if you delete a{{ mediawiki.external(3) }}, a{{ mediawiki.external(4) }} is still a{{ mediawiki.external(4) }} and a{{ mediawiki.external(3) }} is undefined. This holds even if you delete the last element of the array (<code>delete a{{ mediawiki.external('a.length-1') }}</code>).</p>
<p>When the <code>delete</code> operator removes an array element, that element is no longer in the array. In the following example, trees{{ mediawiki.external(3) }} is removed with <code>delete</code>.</p>
<pre class="brush: js">
var trees = ["redwood","bay","cedar","oak","maple"];

delete trees[3];
if (3 in trees) {
    // this does not get executed
}</pre>
<p>If you want an array element to exist but have an undefined value, use the <code>undefined</code> value instead of the <code>delete</code> operator. In the following example, trees{{ mediawiki.external(3) }} is assigned the value undefined, but the array element still exists:</p>
<pre class="brush: js">
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3]=undefined;
if (3 in trees) {
    // this gets executed
}</pre>
<h2 id="Cross-browser_issues">Cross-browser issues</h2>
<p>Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses <code>delete</code> on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property <em>value</em> is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its <em>old</em> position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.</p>
<p>So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.</p>
<h2 id="Specification" name="Specification">External links</h2>
<ul>
  <li>In depth <a href="http://perfectionkills.com/understanding-delete/">analysis on delete</a></li>
</ul>
Revert to this revision