我有一个跟踪DOM上元素移动的数组。因此,在任何时候,由于用户的间歇性更改,DOM(由变量components
表示)可能如下所示:
["app-builder-placeholder",
"app-builder-placeholder",
"app-builder-footer",
"app-builder-navbar",
"app-builder-placeholder"]
["app-builder-placeholder",
"app-builder-placeholder",
"app-builder-navbar",
"app-builder-footer",
"app-builder-placeholder"]
["app-builder-placeholder",
"app-builder-placeholder",
"app-builder-footer",
"app-builder-navbar",
"app-builder-placeholder"]
["app-builder-navbar",
"app-builder-placeholder",
"app-builder-placeholder",
"app-builder-footer",
"app-builder-placeholder"]
我将对数组重新排序以保证以下内容:-app-builder-placeholder
项目在“非” app-builder-xxx
项目之前/之后-两个app-builder-placeholder
项目不能互相跟随
因此,实际上,上面的内容应该看起来像这样:
["app-builder-placeholder",
"app-builder-navbar",
"app-builder-placeholder",
"app-builder-footer",
"app-builder-placeholder"]
或
["app-builder-placeholder",
"app-builder-footer",
"app-builder-placeholder",
"app-builder-navbar",
"app-builder-placeholder"]
因为这是可以对它进行排序的仅有的两种方法。
我当前跟踪DOM更新的代码如下。我将如何扩展它,以便对阵列进行相应的清理。在不符合条件的情况下,可以在非占位符项目之前和之后在现场创建占位符项目,以便重新设计数组以符合条件。
this.options = {
onUpdate: function (e: any) {
let components = [];
for(let i = 0; i < e.target.children.length; i++) {
components.push(e.target.children[i].children[0].children[0].localName)
}
console.log(components);
}
};
这是您可以使用大量阵列助手的一种方式:
let counter = components.length, placeholderName = "app-builder-placeholder";
//calculate new array size with required number of placeholders
let newLength = components.filter(c => c != placeholderName).length*2+1;
//remove excess placeholders
while(newLength > components.length)
components.splice(components.lastIndexOf(placeholderName), 1);
//add placeholders if needed
components.length = newLength;
components.fill(placeholderName,counter);
//iterate and move placeholders to proper locations, preserving order
for(let i = 0, counter = 0; i < components.length; i++)
if(components[i] == placeholderName)
components.splice((counter++)*2, 0, components.splice(i, 1)[0]);