在JavaScript中创建和访问二维数组 [英] Creating and Accessing 2-dimensional arrays in javascript
问题描述
我对如何在javascript中创建和访问二维数组感到困惑.下面是一个数组声明,在其中存储人名,然后存储人名图像的src.当我尝试访问myArray [0] [0]元素时,我得到'D',而当我试图访问myArray [0,0]时,我得到唐纳德·达克.如何访问img src myArray [0] [0] ="assets/scrybe.jpg"?
I'm confused about how to create and access 2-dimensional arrays in javascript. Below is an array declaration in which I'm storing names of people and then the src for their image. When I try to access myArray[0][0] element I get 'D' and when I try to access myArray[0,0], I get Donald Duck. How can I access the img src myArray[0][0] = "assets/scrybe.jpg" ?
JS代码:
var myArray = new Array(1);
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
myArray[0][0] = "assets/scrybe.jpg";
myArray[1][0] = "assets/scrybe.jpg";
myArray[2][0] = "assets/scrybe.jpg";
myArray[3][0] = "assets/scrybe.jpg";
myArray[4][0] = "assets/scrybe.jpg";
myArray[5][0] = "assets/scrybe.jpg";
myArray[6][0] = "assets/scrybe.jpg";
推荐答案
首先,要创建一个数组,最好使用方括号表示法([]
):
Firstly, to create an array, it's better to use the square bracket notation ( []
):
var myArray = [];
这是在JavaScript中模拟多维数组的方式.它是一个数组中的一个或多个数组.
This is the way you emulate a multi-demensional array in JavaScript. It's one or more arrays inside an array.
var myArray = [
[], [] // two arrays
];
如果您要问是否有一种方法可以将数组声明为多维数组,那么不行,没有.您可以像这样访问它们:
If you're asking if there's a way to declare an array as multi-dimensional, then no, there isn't. You can access them like this:
myArray[0][0]; // the 1st element of the first array in myArray
myArray[1][1]; // the 2nd element of the second array in myArray
以下是您可能正在寻找的代码:
Here is the code you were probably looking for:
var myArray = [
["Donald Duck", "assets/scrybe.jpg"],
["Winnie Pooh", "assets/scrybe.jpg"],
["Komal Waseem", "assets/scrybe.jpg"]
[/* and so on...*/]
];
但是,由于您给所有名称提供了相同的URL,因此可以使用for
循环来更快地完成此操作:
But since you're giving all the names the same URL, then you can use a for
loop instead to do this faster:
for (var i = 0; i < myArray.length; i++) {
myArray[i][1] = "assets/scrybe.jpg";
}
这篇关于在JavaScript中创建和访问二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!