[英]For loop in multidimensional javascript array
从现在开始,我使用这个循环遍历数组的元素,即使我将具有各种属性的对象放入其中,它也能正常工作。
var cubes[];
for (i in cubes){
cubes[i].dimension
cubes[i].position_x
ecc..
}
现在,假设 cubes[] 是这样声明的
var cubes[][];
我可以在 JavaScript 中这样做吗? 我怎样才能自动迭代
cubes[0][0]
cubes[0][1]
cubes[0][2]
cubes[1][0]
cubes[1][1]
cubes[1][2]
cubes[2][0]
ecc...
作为一种解决方法,我可以声明:
var cubes[];
var cubes1[];
并分别与两个 arrays 一起工作。这是更好的解决方案吗?
你可以这样做:
var cubes = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for(var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
for(var j = 0; j < cube.length; j++) {
display("cube[" + i + "][" + j + "] = " + cube[j]);
}
}
工作 jsFiddle:
上面的output:
cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
有点太晚了,但这个解决方案很好很整洁
const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
for (let i of arr) {
for (let j of i) {
console.log(j) //Should log numbers from 1 to 10
}
}
或者在你的情况下:
const arr = [[1,2,3],[4,5,6],[7,8,9]]
for (let [d1, d2, d3] of arr) {
console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
}
注意: for... of
循环在 ES6 中是标准化的,所以只有在你有 ES5 Javascript Complier(例如 Babel)时才使用它
另一个注意事项:有替代方案,但它们有一些细微的差异和行为,例如forEach()
、 for...in
、 for...of
和传统for()
。 这取决于您的情况来决定使用哪一个。 (ES6 也有.map()
, .filter()
, .find()
.reduce()
)
循环遍历数组的一种有效方法是内置数组 method.map()
对于一维数组,它看起来像这样:
function HandleOneElement( Cuby ) {
Cuby.dimension
Cuby.position_x
...
}
cubes.map(HandleOneElement) ; // the map function will pass each element
对于二维数组:
cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )
对于任何形式的 n 维数组:
Function.prototype.ArrayFunction = function(param) {
if (param instanceof Array) {
return param.map( Function.prototype.ArrayFunction, this ) ;
}
else return (this)(param) ;
}
HandleOneElement.ArrayFunction(cubes) ;
试试这个:
var i, j;
for (i = 0; i < cubes.length; i++) {
for (j = 0; j < cubes[i].length; j++) {
do whatever with cubes[i][j];
}
}
或者您可以使用“forEach()”替代地执行此操作:
var cubes = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
cubes.forEach(function each(item) {
if (Array.isArray(item)) {
// If is array, continue repeat loop
item.forEach(each);
} else {
console.log(item);
}
});
如果您需要数组的索引,请尝试以下代码:
var i = 0; j = 0;
cubes.forEach(function each(item) {
if (Array.isArray(item)) {
// If is array, continue repeat loop
item.forEach(each);
i++;
j = 0;
} else {
console.log("[" + i + "][" + j + "] = " + item);
j++;
}
});
结果将如下所示:
[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 4
[1][1] = 5
[1][2] = 6
[2][0] = 7
[2][1] = 8
[2][2] = 9
如果您使用的是 ES2015 并且想要定义自己的 object 像二维数组一样迭代,则可以通过以下方式实现迭代器协议:
Symbol.iterator
的@@iterator function 返回...next()
function 的 object...value
(如果有)和 boolean done
如果我们完成迭代,则为 true。一维数组迭代器 function 如下所示:
// our custom Cubes object which implements the iterable protocol
function Cubes() {
this.cubes = [1, 2, 3, 4];
this.numVals = this.cubes.length;
// assign a function to the property Symbol.iterator
// which is a special property that the spread operator
// and for..of construct both search for
this[Symbol.iterator] = function () { // can't take args
var index = -1; // keep an internal count of our index
var self = this; // access vars/methods in object scope
// the @@iterator method must return an object
// with a "next()" property, which will be called
// implicitly to get the next value
return {
// next() must return an object with a "done"
// (and optionally also a "value") property
next: function() {
index++;
// if there's still some values, return next one
if (index < self.numVals) {
return {
value: self.cubes[index],
done: false
};
}
// else there's no more values left, so we're done
// IF YOU FORGET THIS YOU WILL LOOP FOREVER!
return {done: true}
}
};
};
}
现在,我们可以将我们的Cubes
object 视为一个可迭代对象:
var cube = new Cubes(); // construct our cube object
// both call Symbol.iterator function implicitly:
console.log([...cube]); // spread operator
for (var value of cube) { // for..of construct
console.log(value);
}
要创建我们自己的二维可迭代对象,而不是在我们的next()
function 中返回一个值,我们可以返回另一个可迭代对象:
function Cubes() {
this.cubes = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
this.numRows = this.cubes.length;
this.numCols = this.cubes[0].length; // assumes all rows have same length
this[Symbol.iterator] = function () {
var row = -1;
var self = this;
// create a closure that returns an iterator
// on the captured row index
function createColIterator(currentRow) {
var col = -1;
var colIterator = {}
// column iterator implements iterable protocol
colIterator[Symbol.iterator] = function() {
return {next: function() {
col++;
if (col < self.numCols) {
// return raw value
return {
value: self.cubes[currentRow][col],
done: false
};
}
return {done: true};
}};
}
return colIterator;
}
return {next: function() {
row++;
if (row < self.numRows) {
// instead of a value, return another iterator
return {
value: createColIterator(row),
done: false
};
}
return {done: true}
}};
};
}
现在,我们可以使用嵌套迭代:
var cube = new Cubes();
// spread operator returns list of iterators,
// each of which can be spread to get values
var rows = [...cube];
console.log([...rows[0]]);
console.log([...rows[1]]);
console.log([...rows[2]]);
// use map to apply spread operator to each iterable
console.log([...cube].map(function(iterator) {
return [...iterator];
}));
for (var row of cube) {
for (var value of row) {
console.log(value);
}
}
请注意,我们的自定义可迭代对象在所有情况下都不会表现得像二维数组; 例如,我们还没有实现map()
function。这个答案显示了如何实现生成器 map function( 请参阅此处了解迭代器和生成器之间的区别;此外,生成器是 ES2016 功能,而不是 ES2015,因此您如果您使用 babel 进行编译,您将需要更改您的 babel 预设)。
JavaScript 没有此类声明。 这将是:
var cubes = ...
而不管
但你可以这样做:
for(var i = 0; i < cubes.length; i++)
{
for(var j = 0; j < cubes[i].length; j++)
{
}
}
请注意,JavaScript 允许锯齿状的 arrays,例如:
[
[1, 2, 3],
[1, 2, 3, 4]
]
因为 arrays 可以包含任何类型的 object,包括任意长度的数组。
正如MDC所指出的:
“for..in 不应该用于遍历索引顺序很重要的数组”
如果您使用原始语法,则无法保证元素将按数字顺序访问。
forEach()
的 ES6 变体基于icyrock.com的回答。
const cubes = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; cubes.forEach((n, i) => { n.forEach((b, j) => { console.log(`cubes[${i}][${j}] = ${b}`); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.