Below is the code:
var xx=[];
xx['1'] ={'a':'bb','c':'dd'}
debugger;
document.log(xx);
When I print xx it says undefined for key
https://jsfiddle.net/kjuhpgn2/
Can you let me know why "undefined" is coming instead of "1" as key?
Edit:
I got that, it should be {} instead of []
var xx={};
Array indexing start at 0.
What it's saying is that you have nothing at index 0.
When you set xx[1]=something starting from an array of size 0, you set the length of the array to 2, with your something at index 1 and with undefined "filling" the position at index 0.
If what you want is to store a dictionary, then don't use an array but an object as map:
var xx={};
xx['1'] ={'a':'bb','c':'dd'}
This way you wouldn't create a sparse array.
Related
I'm parsing a string to a float, and when I print the type of the variable, I get number. However, if I add the variable to an array, and print it from there, I get string. But if I then index clicks[0], I once again get number
let clicks = []
let latitude = parseFloat(stringCoords.substring(11, 28))
clicks.push(latitude)
console.log(typeof(latitude)) -- prints number
for (var object in clicks) {
console.log(typeof(object)) -- prints string
}
console.log(typeof(clicks[0])) -- prints number
The only thing I'm adding to the clicks array is the latitude variable. I'm confused as to why it's changing types. Please let me know.
The for..in loops through the properties of an object which has the type string. And for..of loops through the values of an iterable object, which has the type of whatever you store in it (In your case, a number).
let clicks = []
let latitude = parseFloat("10.33")
clicks.push(latitude)
console.log(typeof(latitude))
for (var object of clicks) {
console.log(typeof(object))
}
console.log(typeof(clicks[0]))
as 'for(... in ...)' you are navigating through an array, 'object' actually produces the index value of that element, not the element of the current array. When you navigate with the 'clicks.forEach(...)' structure, you access the elements of the array. Therefore, you get a "string", so the operation you do with "typeof(...)" is not on the same elements. One of them gives the array index and the other gives the element of the array.
var myNumb = 5;
var myArr = Array(myNumb);
console.log(myArr.length); // 5
console.log(myArr[0]) // undefined, as well as for myArr[1] myArr[2] myArr[3] myArr[4]
These lines create an array myArray that has a length of 5, but it's also said "an empty array", in fact myArr[0] is undefined, for example.
I can't understand how is possible to have an empty array with a length different from zero. If the array has not items, how can it have a length different from zero?
Positions in an array are still there even if they have no value, they are empty. Say you have the following code:
var myArray = new Array(5);
myArray[4] = 'Hello';
Do you expect 'Hello' to be in position 0 or 4? The answer is, of course, 4. The array has a length of 5, and even if indices 0 to 3 are empty, index 4 has a value.
As per MDN documentation, using the Array constructor yields the following:
If the only argument passed to the Array constructor is an integer
between 0 and (2^32)-1 (inclusive), this returns a new JavaScript array
with its length property set to that number (Note: this implies an
array of arrayLength empty slots, not slots with actual undefined
values). If the argument is any other number, a RangeError exception
is thrown.
JavaScript Array
I got a problem with this simple piece of code which i cant figure out.
Instead of printing the whole array in the console, i get the message "10 undefined". Altough if i put "var i" to 0 or below then it's all good and i get a full list from that number up to 10.
Why wont this work when "i" is set to a number above 0?
Took a picture of my console in chrome to show how it looks like:
var ar = [];
for (var i = 1; i <= 10; i++) {
ar.push(i);
console.log(ar[i]);
}
JavaScript array indices start at 0, not 1. The .push() method adds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.
Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 9.
Each of your console.log(ar[i]) statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefined ten times.
You can log the last element of an array like this:
console.log(ar[ar.length-1]);
Or in your case where you (now) know that i will be one higher than the index that .push() used:
console.log(ar[i-1]);
"10 undefined" means that the console showed "undefined" 10 times.
As thefourtheye says in his comment, you're pushing the value i but the index of the element that you just pushed onto the end of the array is i - 1. This means that each time you console.log(ar[i]) you're logging something that's not yet defined.
This is all because the first element in the array is ar[0], not ar[1]. You can fix your problem by logging like so: console.log(ar[ i - 1 ]);
Because array indices start at zero. The current index is undefined that's why you get those. Try this instead:
var ar = [];
for(var i = 1;i <= 10;i++){
ar.push(i);
console.log(ar[i-1]);
}
I'm practicing the array section of JavaScript Koan and I'm not fully understanding why these answers are correct. I added my assumptions below if someone could please clarify/let me know if I'm wrong :
it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];
expect(array.slice(3, 0)).toEqual([]);
Why wouldn't it at least slice "jelly" since the slice begins with
3? How does the cut off of 0 make it empty instead?
expect(array.slice(3, 100)).toEqual(["jelly"]);
If the cut off index goes beyond what currently exists in the array,
does this mean that a new array created from slice would contain all
indexes starting at 3 until the end of the array?
expect(array.slice(5, 1)).toEqual([undefined];
Will it always be undefined if the starting index doesn't exist in the
array?
});
The second argument to Array.slice() is the upper bound of the slice.
Think of it as array.slice(lowestIndex, highestIndex).
When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.
--EDIT--
Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.
I would like to read some text, consisting of triads of comma separated numbers with one triad per line, into a 2D array. I do not know in advance what the array dimensions will be. I use the following code.
// Read data into a matrix
var inputData = [[]];
while (allTextLines.length>0) {
dataRecord=allTextLines.shift();
entries = dataRecord.split(',');
var xCoord=parseInt(entries.shift());
var yCoord=parseInt(entries.shift());
var zCoord=parseInt(entries.shift());
if (yCoord>=inputData.length) inputData[yCoord]=[];
inputData[yCoord][xCoord]=zCoord;
}
This results in
TypeError: can't convert undefined to object
from Firebug when I try to call
if (yCoord>=inputData.length) inputData[yCoord]=[];
or
inputData[yCoord][xCoord]=zCoord;
I thought that JavaScript arrays could be dynamically resized by assigning a value to an index higher than the current size.
They can be dynamically resized when they exist. There's no such thing as a 2D array in JavaScript. What you create in your initialization is a 1D array with an array in the first element.
All you have to do is check the first dimension before adding something in the second dimension. You're almost doing that now, so it's a minor change:
if (inputData[yCoord] == null) inputData[yuCoord] = [];
You have to do that instead of just checking the length because, if "yCoord" is initially 3, then positions 0, 1, and 2 would still be null after you initialize position 3. Subsequently, a "yCoord" value of 2 would fail your length check, but the slot would be empty nevertheless.
Alternatively, you could do something like this:
for (var yplus = inputData.length; yplus <= yCoord; inputData[yplus++] = []);