도끼 삭제 vs 도끼 = 정의되지 않음
이들 중 하나를 수행하는 데 실질적인 차이가 있습니까?
delete a.x;
vs
a.x = undefined;
어디
a = {
x: 'boo'
};
그것들이 동등하다고 말할 수 있습니까?
(나는 "V8은 delete
더 잘 사용하지 않는 것을 좋아한다" 와 같은 것을 고려하지 않고있다 )
그것들은 동등하지 않습니다. 가장 큰 차이점은
a.x = undefined
즉 a.hasOwnProperty("x")
, 여전히 true를 반환하므로 for in
루프 에 계속 표시됩니다 .Object.keys()
delete a.x
a.hasOwnProperty("x")
거짓을 반환 한다는 의미
그것들이 동일한 방법은 테스트를 통해 속성이 존재하는지 알 수 없다는 것입니다
if (a.x === undefined)
속성이 존재하는지 확인하려는 경우하지 말아야 할 것, 항상 사용해야합니다
// If you want inherited properties
if ('x' in a)
// If you don't want inherited properties
if (a.hasOwnProperty('x'))
프로토 타입 체인 ( zzzzBov에 의해 언급 됨 )에 따라 호출 delete
하면 프로토 타입 체인으로 올라갈 수 있지만, 값을 undefined로 설정하면 체인 된 프로토 타입에서 속성을 찾지 않습니다 http://jsfiddle.net/NEEw4/1/
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
extended.x = "overriding";
console.log(extended.x); // overriding
extended.x = undefined;
console.log(extended.x); // undefined
delete extended.x;
console.log(extended.x); // fromPrototype
상속 된 속성 삭제 삭제 하려는 속성이 상속되면 delete
영향을 미치지 않습니다. 즉, delete
상속 된 속성이 아니라 개체 자체에서 속성 만 삭제합니다.
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
delete extended.x;
console.log(extended.x); // Still fromPrototype
따라서 객체의 값이 정의되지 않았는지 확인해야하는 경우 delete
속성이 상속 될 때 작동하지 않으면 이 경우에 객체 를 설정 (재정의)해야합니다 undefined
. 확인하는 장소가을 사용하지 않으면 확인 hasOwnProperty
하는 모든 곳에서 사용한다고 가정하는 것이 안전하지 않을 수 있습니다hasOwnProperty
질문을 바꾸려면 :
인가
delete a.x
와a.x = undefined
동등한?
아니.
전자는 변수에서 키를 제거하고 나중에 키를 값으로 설정합니다 undefined
. 이것은 객체의 속성을 반복 할 때 hasOwnProperty
와 사용될 때 차이를 만듭니다 .
a = {
x: true
};
a.x = undefined;
a.hasOwnProperty('x'); //true
delete a.x;
a.hasOwnProperty('x'); //false
또한 이것은 프로토 타입 체인이 관련 될 때 큰 차이를 만듭니다.
function Foo() {
this.x = 'instance';
}
Foo.prototype = {
x: 'prototype'
};
a = new Foo();
console.log(a.x); //'instance'
a.x = undefined;
console.log(a.x); //undefined
delete a.x;
console.log(a.x); //'prototype'
If a.x
is a setter function, a.x = undefined
will call the function whereas delete a.x
will not call the function.
The names are a little confusing. a.x = undefined
just sets the property to undefined
, but the property is still there:
> var a = {x: 3};
> a.x = undefined;
> a.constructor.keys(a)
["x"]
delete
actually deletes it:
> var a = {x: 3};
> delete a.x;
> a.constructor.keys(a)
[]
Yes there is a difference. If you use delete a.x
the x isn't any more a property of a, but if you use a.x=undefined
it is a property but its value is undefined.
This REPL from node should illustrate the difference.
> a={ x: 'foo' };
{ x: 'foo' }
> for (var i in a) { console.log(i); };
x
undefined
> a.x=undefined;
undefined
> for (var i in a) { console.log(i); };
x
undefined
> delete a.x;
true
> for (var i in a) { console.log(i); };
undefined
I'm sure you can see the difference between var o1 = {p:undefined};
and var o2 = {};
.
In both cases, o.p
will be undefined
but in the first case, it's because that's the value and in the second case because there is no value.
delete
is the operator that lets you get from o1
(or another object that has a value assigned to its p
property) to o2
that way: delete o1.p;
.
The reverse operation is made by simply assigning a value (undefined
in this example but it could be something else) to the property o1.p = undefined;
.
So no, they are not equivalent.
delete o.p;
will
remove the property
p
from the object if it has onedo nothing otherwise
o.p = undefined;
will
add a property
p
to the object if it doesn't have one yet and set its value toundefined
simply change the value of the property if the object already has it
From a performance perspective, delete
is bad because it modifies the structure of the object (just like adding a new property if you haven't initialized it in the constructor).
Whereas setting the value to undefined
releases the content as well but without forcing to modify the structure.
Object is simply a tree representation, that means, in memory the root points to various memory locations where keys of that object are stored. and that location points to another location where the actual value of that key is stored, or locations where the child keys are stored or locations where the array values are stored.
When you delete any key from an object using delete, actually it deletes link between that key and its parent object and the memory locations of key and its value are freed up to store another information.
When you try to delete any key by setting undefined as its value, then you are just setting its value, not deleting that key. That means that keys memory location is still linked with its parent object and the value if key is undefined.
Using undefined instead of using delete keyword is a bad practice, as it doesn't release memory location of that key.
Even if the key is not present, and you set it as undefined, then that key will get created with value undefined
.
e.g.
var a = {};
a.d = undefined;
console.log(a); // this will print { d: undefined }
delete can't be worked with inherited properties because that property is not the part of that child object.
Using an array, instead of an object, I can showcase that delete uses less heap memory than undefined.
For example, this code will not finish:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
It produces this error:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
So, as you can see undefined
actually takes up heap memory.
However, if you also delete
the ary-item (instead of just setting it to undefined
), the code will slowly finish:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
These are extreme examples, but they make a point about delete
that I haven't seen anyone mention anywhere.
참고URL : https://stackoverflow.com/questions/14967535/delete-a-x-vs-a-x-undefined
'Programming' 카테고리의 다른 글
MySQL에서 빈 값을 허용하는 고유 제한 (0) | 2020.07.11 |
---|---|
객체를 JSON 문자열로 변환 (0) | 2020.07.11 |
정적 클래스 멤버에서 해석되지 않은 외부 기호 (0) | 2020.07.11 |
동적 객체의 멤버를 어떻게 반영합니까? (0) | 2020.07.11 |
$ PATH 변수에서 중복 경로 제거 (0) | 2020.07.11 |