Javascript array showing 2 values in console, only 1 when accessed - javascript

I have a Javascript array of arrays.
When I print the array to the console I get:
console.log(my_array_of_arrays);
Array[2] ->, Array[2] ->,
0: 678 0: 1168
1: 865 1: 1370
length: 2 length: 2
This shows that there are 2 items in both arrays.
Then when I access last item in the array by accessing either ".length" or my_array[1], it tells me that the array only has 1 item, and the 2nd item is undefined.
var my_array = my_array_of_arrays[1];
console.log(my_array, my_array.length, my_array[0], my_array[1]);
[1168, 1370], 1, 1168, undefined
As you can see this happens if I do it all in the same console log statement, so I know the array isn't changing.
What could be going on here, I am completely stumped.
Edited for clarity

From the console in Chrome
spo = [000,111]
(spo[0] == 000) //true
(spo[1] == 111) //true
I am not sure what else you can be doing = /

I have discovered that further down the function the value my_array[2] wasn't being set until after I called console.log().
However this has shown some weird behavior of console.log().
It doesn't necessarily show the live value of the array at the time of calling.
eg.
var my_array = [111];
console.log(my_array);
my_array[1] = 222;
This prints:
[111, 222]
When I was expecting it to print:
[111]
This means that console.log() doesn't always show the "live" representation of the real values at the time of the call.
However if I access a property on the array it will show the live values.
Example:
var my_array = [111];
console.log(my_array.length, my_array[1]);
my_array[1] = 222;
This prints as expected:
1, undefined
Guess I can't trust the console as well as I have been!

Related

Why is destructuring and concatenation leaving different types of undefined in array? [duplicate]

I'm doing some small experiments based on this blog entry.
I am doing this research in Google Chrome's debugger and here comes the hard part.
I get the fact that I can't delete local variables (since they are not object attributes). I get that I can 'read out' all of the parameters passed to a function from the array called 'arguments'. I even get it that I can't delete and array's element, only achieve to have array[0] have a value of undefined.
Can somebody explain to me what undefined x 1 means on the embedded image?
And when I overwrite the function foo to return the arguments[0], then I get the usual and 'normal' undefined.
This is only an experiment, but seems interresting, does anybody know what undefined x 1 refers to?
That seems to be Chrome's new way of displaying uninitialized indexes in arrays (and array-like objects):
> Array(100)
[undefined × 100]
Which is certainly better than printing [undefined, undefined, undefined,...] or however it was before.
Although, if there is only one undefined value, they could drop the x 1.
Newer versions of Chrome use empty instead of undefined to make the difference a bit clearer.
For example, entering [,,undefined,,] in the DevTools console results in:
▼(4) [empty × 2, undefined, empty]
2: undefined
length: 4
▶__proto__: Array(0)
Google Chrome seems to choose to display sparse array using this undefined x n notation. It will show [undefined, undefined] if it is not a sparse array:
var arr = new Array(2);
console.log(arr);
var arr2 = [];
arr2[3] = 123;
console.log(arr2);
var arr3 = [,,,];
console.log(arr3)
var arr4 = [,];
console.log(arr4)
var arr5 = [undefined, undefined]
console.log(arr5)
var arr6 = [undefined]
console.log(arr6)
arr1 to arr4 are all sparse arrays, while arr5 and arr6 are not. Chrome will show them as:
[undefined × 2]
[undefined × 3, 123]
[undefined × 3]
[undefined × 1]
[undefined, undefined]
[undefined]
note the [undefined x 1] for the sparse array.
Since you deleted an element, it follows that: If you delete an element from an array, the array becomes sparse.
Here is how it looks, Type this code into chrome devtools console:-
arr = new Array(4);
arr[2] = "adf";
console.log(arr); // [undefined × 2, "adf", undefined × 1]
See the first two consecutive "undefined" that are represented by *2, to show that there are two consecutive undefined there
It just happened to me too. Open the same thing in another browser and output/log the array to the console. As long as it works in both crome and in firefox the same way (as in accessing the elements works fine even if the output has the undefinedx1), I consider it some kind of bug in Chrome not refreshing something internally. You can actually test it this way:
I was adding elements to an array, and firing console.log() to log the element, to check if it was undefined or not. They were all defined.
After push() I logged the array and it seemed that when this happened, it was always the last one being undefined x 1 on Chrome.
Then I tried logging it more times and also later, but with the same result.
However when I accessed (for the sake of output), the element by its index, it returned the proper value (funny).
After that I logged the array again and it said the last index was undefined x 1 (the very one I just accessed directly with success!).
Then I did a for loop on the array, logging or using each element, all showed up fine.
Then another log on the array, still buggy.
The code I'm originally using has checks for undefined and they didn't fire, but I was seeing all these undefineds in the console and it was bugging me (no pun intended).
Also worth reading: Unitialized variables in an array when using only Array.push? I'm using pop() too in my code and it's a reasonable explanation that the console log actually represents a different state in time (when the code is 'halted').

From array of objects, extract value at certain index --> undefined

I have a problem in getting a value from a certain index form an array of objects.
The Array looks something like that:
[Object, Object, Object, Object]
When I open them in the Crome console, it looks like this:
The thing is that I want the value of uuid from one of this Objects.
If I write console.log(this.myArray[0].uuid) I am getting the uuid from index 0.
But as soon as I write console.log(this.myArray[index].uuid), where index is a number, I only get undefined.
I already tried
var test = _.map(this.myArray,"uuid");
console.log(test[index].uuid)
but that only get's me undefined
Can someone please help me?
if you want index loop array like this
for(var i = 0;i<this.myArray.length;i++){
console.log(this.myArray[i].uuid)
}
I think you're mistaken on how _.map works when passing a key:
let arr = [
{ index: 4, name: 'Hello' },
{ index: 9, name: 'World' }
]
_.map(arr, 'index') // produces [4, 9]
As a result, if you wish to access the index value, you would do so directly from the array itself.
let indexes = _.map(arr, 'index')
indexes[0] // 4
I have already tried
var test = _.map(this.mycards,"uuid");
console.log(test);
console.log(test[index]);
the fist console.log
console.log(test);
results in an Array with all the uuid's:
["3c539a73-d569-4512-b558-291164f34529", "b6920edc-77a8-4ac6-8fa3-65c7b05ea556", "9d8afb0c-5268-44a1-b02f-0772357025d0", "4a33b232-7c1d-4ee7-b53c-3615c0fbd7d3", "68888839-a888-4595-9be9-3ec07fe35850", "0ab242ca-e6e1-4497-871e-196c3a05e0ec", "0c311bc6-c396-45a9-865e-19cdc8800bf7", "3add00ad-7371-417a-89ae-e4f0966ab503", "ac503849-5476-4710-9c2e-a514a178c4f5"]
but with console.log(test[index]); I get again undefined as a result.
The thing is, that my method looks something like that:
event(index, eventObject) {
...
};
and index is always a number, which I don't know, because it differs every time the method is called.
But for some reason when I put in a number instead of index (which is also a number) like this this.myArray[0].uuid I get the a result.
But when I change to this.myArray[index].uuid I get undefined.
I even tried parseInt(index) but that also didn't work.

javascript array unsure property array[index] = true/false

I came across this, understood it but still did not know what javascript property it was:
var array = [];
array[1] = true;
array[5] = true;
console.log(array) #=> [true, true]
array[0] #=> undefined
array[1] #=> true
array[2] #=> undefined
array[5] #=> true
Can someone explain this for me? Thanks
Standard arrays in JavaScript aren't really arrays at all, and one effect of that is that they're inherently sparse. That is, an array can have empty slots in it.
That's what you're creating there. After your first three lines, you have an array with two entries in it, at indexes 1 and 5, and a bunch of completely empty slots (indexes 0, 2, 3, 4). Its length property would be 6. When you try to retrieve an element that doesn't exist from an array, you get the value undefined. (This is just a specific case of JavaScript's general behavior: If you try to retrieve an object property that doesn't exist, you get the value undefined.)
The output of console.log with a sparse array will vary depending on what the implementation of console.log does with them. The comments on the question suggest that there are various different ways the console may show the array. You might look at using console.log(array.join()) to get more consistent results. That would give you ,true,,,,true, because it shows blanks for array entries that don't exist (or that contain the value undefined, but in your case, they don't exist).

What delete really means in NodeJS in arrays?

Reading the answers to this question I understand that delete sets undefined value for the element.
So, if we have an array: a = [1, 2, 3] (at least) on the client side using delete a[1] the array would become [1, undefined x 1, 3] that is true, on the client side.
What happens in NodeJS?
But testing same operation on NodeJS (server side) I get the following:
$ node
> a = [1, 2, 3]
[ 1, 2, 3 ]
> delete a[1]
true
> a
[ 1, , 3 ]
> a[1] = undefined
undefined
> a
[ 1, undefined, 3 ]
>
So, a[1] = undefined sets undefined value. But what does the space mean between the two commas ([1, , 3])? delete put it! Why?
I guess that the space means undefined, but why it doesn't appear as undefined only I set it as undefined?
Why is this happening?
When you use delete on an array entry, it removes that entry from the array. The array length is not changed, but that slot in the array is gone. If you try to look at the value of that slot it will show as undefined though deleting it is not quite the same as setting it to undefined. You can read about deleting an array entry here (scroll down to the subtitle "Deleting Array Elements").
This reference also explains the difference between using delete on an array entry vs. setting it to undefined. The difference is subtle and only makes a difference in a few situations. Here's an example from that article:
// using delete
var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
// setting to undefined
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3]=undefined;
if (3 in trees) {
// this gets executed
}
So, this console output:
[ 1, , 3 ]
is showing you that the second array entry is missing (it's gone completely).
See this article http://perfectionkills.com/understanding-delete/ for a full run-down of how the delete operator works in other circumstances.
Array indexes at language level work like any other properties.
When you access a property that's not there, the proto chain is walked until a result is found or undefined is returned if nothing is found. But you can also use undefined as a normal value.
There can be major differences, eg:
Array.prototype[1] = 15;
var a = [1, 2, 3];
delete a[1];
//protip: the above can be written as `var a = [1,,3]`
var b = [1, undefined, 3];
//Logs 15 and undefined
console.log(a[1], b[1]);
In a, because the property 1 is not there, the prototype is checked and the value 15 is found.
In b, because the property 1 is there, the value of the property (undefined) is just directly returned.
Also the console formatted output for an array is usually different between environments but that doesn't really change what is actually going on.

Array containing objects has wrong length

I have an array like:
errors = [ {...}, {...}, {...} ]
It's an instanceof array, yet it only returns 1 for .length?
Relevant code:
if(data.error){
errors.push({'element':ele,error:data.error});
}
//Above is looped a few times and there are N number of errors now inside
console.log(errors) //Returns 2+ objects like {...}, {...}
console.log(errors.length) //Returns 1
For Uzi and Muirbot, here's the errors array:
[
Object
element: b.fn.b.init[1]
error: "You must enter "example" into the field to pass"
__proto__: Object
,
Object
element: b.fn.b.init[1]
error: "Crap!"
__proto__: Object
It is correct, this code:
var errors = new Array();
errors.push({'element':'ele', error:'data.error'});
...adds ONE object to the array. The object has two properties.
It's possible your code is executing in an order other than what you're expecting. ie, when you log both errors and errors.length, errors does contain only 1 object. But after that you are adding to the errors array, and only after that are you looking at the console. At that point you could see a larger array in errors for two reasons - first, your actual code isn't logging errors but some object that contains errors. In that case the console display is live, and will show you not what was in errors at the time, but what is in it now. Alternatively, the console could just be taking some time to log errors.
Without more code I can't be sure if this is the case. But you could verify it by replacing console.log(errors); with console.log(errors[1]);. If errors is really only 1 long at the time, it will log undefined.
The problem was that Chrome's Web Inspector's console.log is an async event. So, the length was a property lookup so it gave that back instantly, but the object with two items inside was held off until the rest of the events had fired.
In the future I, and others with this issue, should use debugger; instead.
is it an Array object or something that resembles it?
arrays do work:
> a = [{a:1}, {b:2}]
[Object, Object]
> a.length
2
you'll have to provide more code.
and now that you've provided the relevant code, the correct answer is what Steve Wellens said (which was downvoted, by the way).
Array.push adds a single element, objects may have more than one key but they're still a single object so your real case was different from your original example, which of course works.
another possibility:
> a = []
[]
> a.length = 2
2
> a
[]
> a.length
2
> a instanceof Array
true

Categories

Resources