LoginSignup
0
0

More than 1 year has passed since last update.

輪読メモ|JavaScript|オブジェクトと配列におけるdelete演算子の結果

Posted at

開眼! JavaScript――言語仕様から学ぶJavaScriptの本質を輪読会で読み進めている最中です。

本書の中で紹介されていたdelete演算子について、Chromeのデベロッパーコンソールを利用して復習・確認した📝になります。

オブジェクトと配列に対してdelete演算子を利用する

オブジェクトの場合
const obj = {1:1, 2:2, 3:3, 4:4};
console.log(obj);  // {1: 1, 2: 2, 3: 3, 4: 4}

delete obj['2'];  // true
console.log(obj);  // {1: 1, 3: 3, 4: 4}
console.log(obj[2]);  // undefined

const obj2 = {test: 'aaa'};
console.log(obj2);  // {test: 'aaa'}
obj2[test] = undefined;
console.log(obj2);  // {test: undefined}
obj2[test] = null;
console.log(obj2);  // {test: null}

delete演算子はオブジェクトからプロパティの存在を削除する唯一の方法。
プロパティの値にundefinednullを設定しても、プロパティ値を変更することにすぎない。削除するにはdelete演算子を利用する必要がある。
image.png

配列の場合
const ary = [1,2,3,4,5];
console.log(ary);  // (5) [1, 2, 3, 4, 5]

delete ary[2];  // true
console.log(ary);  // (5) [1, 2, empty, 4, 5]
console.log(ary[2]);  // undefined

console.log(ary.length); // 5
delete ary.length;  // false
console.log(ary.length); // 5

配列の削除も可能だが、配列の指定要素はundefinedになり、lengthは維持される。
プロトタイプチェーンで継承するプロパティは削除できない。

2次元配列の場合
const ary_two = [[1,2,3,4],[5,6,7,8]];
console.log(ary_two); // (2) [Array(4), Array(4)]

delete ary_two[1][2] // true
console.log(ary_two); // (2) [Array(4), Array(4)]
/*
(2) [Array(4), Array(4)]
  0: (4) [1, 2, 3, 4]
  1: (4) [5, 6, empty, 8]
*/

delete ary_two[1] // true
console.log(ary_two); // (2) [Array(4), empty]
/*
(2) [Array(4), empty]
  0: (4) [1, 2, 3, 4]
*/

2次元配列も配列と同様入れ物としての長さは元のまま残ってしまう。

配列とオブジェクトの組み合わせ

image.png
オブジェクトのプロパティであれば削除可能だが、配列の場合は通常の配列と同様に入れ物の形は残ってしまう。


現時点でdelete演算子を利用する機会が無かったために、現環境における運用のイメージは湧いていないが、配列とオブジェクトでdelete演算子を利用した場合の結果が異なることを理解することができた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0