gpt4 book ai didi

Javascript:改进四个嵌套循环?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:04 25 4
gpt4 key购买 nike

我有一个包含嵌套数组的复杂对象数组。下面的工作是提取某些对象,但它是我写过的最丑陋的东西之一。

是否有一些 javascript 黑魔法可以优雅地做到这一点?

function getEighthInsertionBlocks() {
var struct = Lifestyle.Pagination.structure;
var blocks = [];
for (var i = 0; i<struct.length; i++) {
var page = struct[i];
var layers = page.children;
for (var j=0; j<layers.length; j++) {
var layer = layers[j];
if (layer.className === 'EighthPageLayer' ) {
var rows = layer.children;
for (var k=0; k<rows.length; k++) {
var row = rows[k];
eBlocks = row.children;
for (var l=0; l<eBlocks.length; l++) {
blocks.push(eBlocks[l]);
}
}
}
}
}

return blocks;
}

并不是说我是 code golf 的忠实粉丝,而是......这太可怕了。

最佳答案

您可以编写一个通用迭代器,它将代码缩减为顺序 block :

var iterator = function(collection, callback){
var length = collection.length;
var results = [];
var result;
for (var i = 0; i < collection.length; i++){
result = callback(colleciton[i], i);
if (result){
results = results.concat(result);
}
}
return results;
};

function getEighthInsertionBlocks() {
var struct = Lifestyle.Pagination.structure;
var layers = iterator(struct, function(page){ return page.children; });
var rows = iterator(layers, function(layer){
return layer.className === 'EighthPageLayer' ? layer.children : null;
});
return iterator(rows, function(eBlocks, index){ return eblocks[index]; });
}

关于Javascript:改进四个嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com