[英]How does a mutable array works in js?
i'm Learning Javascript from multiple ressources like FCC where i can't Understand one concept with the mutable arrays. 我正在从FCC等多种资源中学习Javascript,在这些资源中我无法理解可变数组的一个概念。 I've got an example :
我有一个例子:
var myArray = [1,2,3];
myArray[0]=3; //[3,2,3]
var ourArray = [1,2,3];
ourArray[1] = 3; //[1,3,3]
i can't get how the [3,2,3]
and [1,3,3]
are created. 我不知道如何创建
[3,2,3]
和[1,3,3]
。
thanks for your help 谢谢你的帮助
ok, got it but what if my code looks like this : 好的,知道了,但是如果我的代码看起来像这样:
var arr = [ [1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14] ];
arr[3]; // equals [[10,11,12], 13, 14] arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11 how the arr[3] or arr[3][0] work ?
Arrays in JS starts with 0 index. JS中的数组以0索引开头。
In the first case you're replacing 1 with 3 在第一种情况下,您将1替换为3
[1, 2, 3]
^
3
[0, 1, 2] <- indexes
In the second case, you're replacing 2 with 3 在第二种情况下,您将2替换为3
[1, 2, 3]
^
3
[0, 1, 2] <- indexes
Mutable just means that each element in the array can be changed. 可变只是意味着可以更改数组中的每个元素。 The number inside the brackets is the order starting with 0;
括号内的数字是从0开始的顺序;
So originally myArray[0] is 1, myArray[1] is 2, myArray[2] is 3 When you do myArray[0] = 3 it sets the value in the first spot to 3, hence getting 3,2,3 因此,最初myArray [0]为1,myArray [1]为2,myArray [2]为3,当您执行myArray [0] = 3时,它将第一个点的值设置为3,因此得到3,2,3
当您在此处写入myArray[0]=3
,您要在该数组中设置一个与ourArray[1]
相同的特定位置的值,以便在该数组中使用新值进行更改,以便控制台为您提供具有新值的数组就像在您的示例中一样,您使用名称myArray
和ourArray
进行了定义。
Let me go through your code line by line, 让我逐行浏览您的代码,
var myArray = [1,2,3];
creates a myArray with [1, 2, 3] 用[1、2、3]创建一个myArray
myArray[0]=3;
index 0 of myArray is set to 3; myArray的索引0设置为3;
so myarray holds [3, 2, 3] 所以myarray持有[3,2,3]
var ourArray = [1,2,3];
ourArray is created with [1, 2, 3] ourArray用[1、2、3]创建
ourArray[1] = 3;
index 1 of our array is set to 3; 数组的索引1设置为3; so our array holds [1, 3, 3]
所以我们的数组保存[1、3、3]
Please note that index starts with 0 and not with 1. 请注意,索引以0开头,而不是以1开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.