0

What is the logic behind these digits being printed from this array?

var a = [1,3,4,6,8]; var b = [7,3,2,9,5]; var x = b.concat(a); for (let i in x){ console.log(x[x[i]]); } console.log(x); Edit: why does this print 4? Edit2: So the array looks like this after being concatenated [ 7, 3, 2, 9, 5, 1, 3, 4, 6, 8 ] But when I run the loop printing x[x[i]] the output is 4 9 2 8 1 3 9 5 3 6 I don't understand how that relates to the first array

28th Oct 2019, 12:04 PM
Steven Milbourne
Steven Milbourne - avatar
7 Respuestas
+ 3
After concatenation, x holds [1, 3, 4, 6, 8, 7, 3, 2, 9, 5] Now in JavaScript arrays are internally stored as object, where index is the key and element at that index is the value {"0": 1, "1": 3, "2": 4, "3": 6, "4": 8, "5": 7, "6": 3, "7": 2, "8": 9, "9": 5} Now, you use in to iterate over objects So...for(let i in x ) { console.log(i);//is the key console.lig(x[i]);//is the value of the key }
28th Oct 2019, 12:18 PM
Rishi Anand
Rishi Anand - avatar
+ 1
You can think of x[x[3]] as var index = x[3], console.log(x[index]),
28th Oct 2019, 5:45 PM
ODLNT
ODLNT - avatar
0
I've edited the question because I didn't understand why it prints 4
28th Oct 2019, 12:19 PM
Steven Milbourne
Steven Milbourne - avatar
0
b.concat(a) means adding array a to the end on array b https://code.sololearn.com/W25I2sDk6qMv/#js
28th Oct 2019, 2:46 PM
ODLNT
ODLNT - avatar
0
So the array looks like this after being concatenated [ 7, 3, 2, 9, 5, 1, 3, 4, 6, 8 ] But when I run the loop printing x[x[i]] the output is 4 9 2 8 1 3 9 5 3 6 I don't understand how that relates to the first array If I asked what would x[x[3]] print how would you figure out the answer is 8?
28th Oct 2019, 3:54 PM
Steven Milbourne
Steven Milbourne - avatar
0
Thank you that finally clicked for me
28th Oct 2019, 5:54 PM
Steven Milbourne
Steven Milbourne - avatar
0
You are welcome
28th Oct 2019, 6:05 PM
ODLNT
ODLNT - avatar