i have following code outputs length of array, deletes it, , outputs new length:
console.log($scope.advicelist.activeadvices.length); // *1* $scope.advicelist.activeadvices.splice(id,1); // *id parameter* console.log($scope.advicelist.activeadvices.length); // *0* console.log($scope.advicelist.activeadvices.length); // *1* delete $scope.advicelist.activeadvices[id]; console.log($scope.advicelist.activeadvices.length); // *0* console.log($scope.advicelist.activeadvices); // *[]*
after deletion, array correctly displayed empty. length, however, still 1.
delete
"lower level" operator. directly works on object, doesn't "know" array. using delete
doesn't trigger routine recompute array length.
other answers here claim value of property set undfined
, incorrect. simple test shows that:
var = [1]; delete a[0]; console.dir(a);
and compare happens if set value undefined
:
var = [1]; a[0] = undefined; console.dir(a);
for more solid proof, lets have @ specification:
when [[delete]] internal method of o called property name p , boolean flag throw, following steps taken:
- let desc result of calling [[getownproperty]] internal method of o property name p.
- if desc undefined, return true.
- if desc.[[configurable]] true, then
a. remove own property name p o.
b. return true.- else if throw, throw typeerror exception.
- return false.
nowhere said value of property set undefined
.
the consoles of different browsers might show different representations of array. in particular example, can argue whether should []
or [undefined]
.
[]
(chrome) seems make sense because array doesn't have elements, there no properties numeric names. however, when access.length
property,1
, can confusing.
not long ago, chrome used a representation[undefined x 5]
indicate array of length 5 without elements. think solution.[undefined]
(firefox) makes sense because array of length 1 , accessingarr[0]
returnsundefined
(butarr[10]
).however,arr.hasownproperty(0)
false
, if array contains valueundefined
, how can distinguished empty array of length 1 solely representation (answer: can't).
the bottom line is: don't trust console.log
much. rather use console.dir
if want exact representation.