我正在尝试创建一个简单的算法来构建具有动态长度的数组。
然后,它将逐个替换一个项目,然后是两个、三个,依此类推,直到只剩下第一个和最后一个项目。
像这样:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
我制作了一个简单的演示来展示我正在尝试做的事情。
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
它工作正常,唯一的问题是它出了故障。 现在它似乎只按星号数量进行迭代,然后按索引进行迭代。我需要它来做相反的事情。
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
如果有人可以提供帮助那就太好了,因为我真的很茫然!
最佳答案
这应该可以完成。
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
关于javascript - 实现这个序列的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724570/