我试图找出为什么我无法每3秒一次获得每个项目数组的单个值。
如您所见,我正在获取整个数组值,而不是分别获取它们。我需要它来分别获取和结束第一级阵列的每个级别的控制台日志
var imgs = [
[
['#fff', '#eee'],
['#117A65', '#E74C3C'],
['#F39C12', '#AF7AC5']
],
[
['#7B241C ', '#eee'],
['#117A65', '#909497 ']
],
[
['#17A589', '#626567']
],
[
['#5499C7', '#eee'],
['#117A65', '#884EA0']
],
];
for (let i = 0; i < imgs.length; i++) {
for (let j = 0; j < imgs[i].length; j++) {
for (let b = 0; b < imgs[j].length; b++) {
(function(index) {
setTimeout(function() {
console.log(imgs[i][j][b]);
}, i * 3000);
})(i);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 0 :(得分:3)
仅flat
个数组并使用一个循环:
var imgs=[[['#fff','#eee'],['#117A65','#E74C3C'],['#F39C12','#AF7AC5']],[['#7B241C ','#eee'],['#117A65','#909497 ']],[['#17A589','#626567']],[['#5499C7','#eee'],['#117A65','#884EA0']]];
const flattened = imgs.flat(2);
for (let i = 0; i < flattened.length; i++) {
console.log(flattened[i]);
}
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果您需要在每个第一级迭代后执行某些操作,则应使用经典的for
循环:
var imgs=[[['#fff','#eee'],['#117A65','#E74C3C'],['#F39C12','#AF7AC5']],[['#7B241C ','#eee'],['#117A65','#909497 ']],[['#17A589','#626567']],[['#5499C7','#eee'],['#117A65','#884EA0']]];
for (let i = 0; i < imgs.length; i++) {
for (let j = 0; j < imgs[i].length; j++) {
for (let k = 0; k < imgs[i][j].length; k++) {
console.log(imgs[i][j][k]);
}
}
console.log("First level iteration complete - callback here!");
}
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>