This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 25 days ago.
In the code below you see that it recognises arrayi as array - i.
Is this system built into js? I was experementing and it didn't function when I wrote array(i) instead of arrayi. The question then extends beyond all to ask if you could do iarray, ariray, arrayii or array(i*i) (just want to figure out the syntax of how this works).
var array = []
var arrayAmount = prompt("Select number of array")
for (var i = 0; i < arrayAmount; i++) {
var arrayi = array
arrayi.push([prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-elemet 2"], ])
console.log(arrayi)
}
console.log(array1)
Edit: I checked if the code would work if the for loop declares its own arrays instead of copying another array. Turns out it did not work and declared arrayi as arrayi instead of array1 or array2
You're confusing several JS concepts. I'll make some assumptions to explain some things, but feel free to correct me and I'll adjust my answer.
I believe you meant to assign a value at a particular index in the array, but what you ended up doing is creating a variable arrayi that is a reference to array:
var array = [];
array[1] = "foo";
console.log(array); // [undefined, "foo"]
What you did instead was create a reference, which means two different variable names will evaluate to the same object/array:
var array = [];
var reference_to_array = array;
reference_to_array.push("foo");
console.log(array); // ["foo"]
console.log(reference_to_array); // ["foo"]
Your original question includes: "and it didn't function when I wrote array(i) instead of arrayi".
To which the answer is: array(i) should be changed to array[i] when working with arrays.
Instead of fixing your original issue, you ended up creating new variables.
To fix your original code:
var array = [];
// Added parsing to an integer
var arrayAmount = parseInt(prompt("How many items do you want to add to the array?"));
for (var i = 0; i < arrayAmount; i++) {
// Method 1: directly access the index
//array[i] = [ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ];
// Method 2 (Recommended): push a new element onto the end of the array
array.push([ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ]);
// Log this element
console.log(array[i]);
}
Related
This question already has answers here:
Push is overwriting previous data in array
(2 answers)
Closed 5 days ago.
I have the following code. Essentially what I do is I have a loop, and within the loop I have logic that creates a few values. I want to insert those values into an Object, and then insert that Object into an Array.
Now in each iteration, the object values change, so in case this loop runs 2 times, I'd expect to have two different objects.
Problem is, on first iteration, I push a distinctive object into an array, and then on the 2nd iteration, I have a new object with different values, but after I do .push - it overwrites my earlier entry with the new values, and insert a new object into the array.
I.E. I end up have 2 identical objects in the array. What is happening?
var arr = [];
var filObj={};
for (var i = 0; i<3; i++){ //looping
//I do some logic and derive a few fields and insert them into my `filObj`
filObj['col1'] = 'Hello';
filObj['col2'] = 'Yellow';
filObj['col3'] = 'Seven';
arr.push(filObj);
}
You are inserting the same object in each iteration.
The fix is to a create a new object every time.
var arr = [];
for (var i = 0; i<3; i++){ //looping
var filObj={};
//I do some logic and derive a few fields and insert them into my `filObj`
filObj['col1'] = 'Hello';
filObj['col2'] = 'Yellow';
filObj['col3'] = 'Seven';
arr.push(filObj);
}
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
I tried to create a 2-dimensional array in javascript. (Actually, the code is written in typescript and will be used to style DOM Elements with Angular2 but, as far as I am concerned, it shouldn't have any effect on the result in this case.)
First way:
arrayi = Array(10).fill(Array(20).fill(-1))
Second way:
array = [];
for(var i: number = 0; i < 10; i++) {
array[i] = [];
for(var j: number = 0; j< 20; j++) {
array[i][j] = -1;
}
}
If I call array[1][2] = 2; it does what I expected, what means setting one element in the 2-dimensional array to 2.
However, if I call arrayi[1][2] = 2; every element arrayi[x][2] will be set to 2. (With x element {0,1,2,...,9})
Why is that? I don't understand it. So it would be nice if someone could explain it to me.
The arrays are defined as array: number[][] and arrayi: number[][] in typescript.
arrayi = Array(10).fill(Array(20).fill(-1)) fills with the same array.
You can even rewrite it like this
const arr1 = Array(20).fill(-1)
const arrayi = Array(10).fill(arr1)
console.log(arrayi.every(item => item === arr1)) //true
The reason is that you create one instance of array with 20 elements and put this single instance into each element of root array
This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));
This question already has answers here:
How to get property value in js object when key is unknown
(3 answers)
Closed 3 years ago.
Using the following generated array example structure, how can I loop through and extract the property names and their associated values from each object?
[{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}]
The number of objects may change, and the property names will not be consistent.
You can use Object.keys()[0] to get the key, then use the key to get the value.
JSFiddle
var myData = [{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}];
for (var i = 0; i < myData.length; i++) {
var myObject = myData[i];
var firstKey = Object.keys(myObject)[0];
var value = myObject[firstKey];
console.log(firstKey + ": " + value);
}
See also: ECMAScript® Language Specification: 15.2.3.14 Object.keys ( O )
Expanding on #AR7's answer, in the case that there may be multiple properties in each of the objects you can cache the object returned by Object.keys() and loop through each property within the array loop.
Using the method below, you can handle any number of properties within the object.
I realize this may not be any more useful in this specific situation than the aforementioned answer, but hopefully it will be useful to future viewers.
JSFiddle
var a = [
{ "bg_2":"0.50", "bg_7":"0.10", "bg_12":"0.20"},
{ "bg_2":"0.50", "bg_7":"0.10"},
{ "bg_2":"0.50"}
];
a.forEach(function(o){
console.log(o);
var k = Object.keys(o);
for(var i in k)
console.log(k[i], ':', o[k[i]]);
});