Delete item from array , why for and for in output are different?
-
11-12-2019 - |
Question
var arr = ["a", "b", "c",null,undefined];
delete arr[0];
for (var i = 0,j=arr.length; i < j; i++) {
console.log(arr[i]);
/*
undefined
b
c
null
undefined
*/
}
for (var o in arr) {
console.log(arr[o]);
/*
b
c
null
undefined
*/
}
who can tell me why the output is different?
Solution
you have access by key;
array index is key of array object
using delete keyword, remove object key because
delete arr[0]; // key "0" deleted!
ok?
and see this
var arr = ["a", "b", "c",null,undefined];
delete arr[0]; // key "0" deleted!
// access by i, with key : 0
for (var i = 0,j=arr.length; i < j; i++) {
console.log(i);
/*
0
1
2
3
4
*/
}
// access by object key, without key : 0
for (var o in arr) {
console.log(o);
/*
1
2
3
4
*/
}
good luck!
OTHER TIPS
Actually delete
doesn't remove the element from the array it only sets the element as undefined, to remove an item from an array use splice
as follows
var arr = ["a", "b", "c",null,undefined];
arr.splice(0, 1);
Now your array is as follows
["b", "c", null, undefined]
But you used delete
to remove the first item from the array as follows
delete arr[0];
and after that your array looked like as follows
[undefined × 1, "b", "c", null, undefined]
So, In your first loop you used
for (var i = 0,j=arr.length; i < j; i++) {
console.log(arr[i]);
}
It iterated array using index of the array so (in the loop for the the first time) arr[i]
means arr[0]
which is undefined
and in your second loop you used
for (var o in arr) {
console.log(arr[o]);
}
This is actually ideal to use with an object to loop but you used an array ,well I think it should also display other properties of the array and really confused how did you get only these (b c null undefined)
values unless you use hasOwnProperty
for (var o in arr) {
if(arr.hasOwnProperty(o)) console.log(arr[o]);
}
Whatever, it iterates all available properties of an object and should not be used with an array. Check this fiddle to understand how hasOwnProperty
works and what you should get without using this method when iterating an array
using for in
.
Given an empty array array = []
, array[0]
returns undefined
, becase there is no item stored in position 0. After deleting arr[0]
, there is no data there. Loop with for .. in ..
iterate all elements in array, so it returns b c null undefined
. More specific, for .. in ..
loops properties in an object. So, if you assign a new property, say name
to arr
, arr.name = "an array"
, it shall be printed in for .. in ..
loop.