我正在尝试创建一个函数,该函数接受数组中的所有点,并返回在每对相邻点之间有一个附加点的数组。例如,从(2,10)开始,我将获得以下迭代到列表中:
(2, 14)
(2, 8, 14)
(2, 5, 8, 11, 14)
(2, 3.5, 5, 6.5, 8, 9.5, 11, 12.5, 14)
我的代码:
var Width = 1000
var Height = 1000
const svg = document.getElementById('svg1')
svg.setAttribute('width', Width)
svg.setAttribute('height', Height)
var seg = function(point) {
var segment = document.createElementNS("http://www.w3.org/2000/svg", "circle")
segment.setAttribute("cx", point.x)
segment.setAttribute("cy", point.y)
segment.setAttribute("r", 1)
segment.setAttribute("fill", "none")
segment.setAttribute('stroke', "#f00")
segment.setAttribute('stroke-width', 0.5)
svg.appendChild(segment)
}
const mid = function(pa, pb) {
let cx = (pa.x + pb.x) / 2
let cy = (pa.y + pb.y) / 2
return {
x: cx,
y: cy
}
}
var testarray = [{
x: 0,
y: 100
}, {
x: 400,
y: 50
}]
const split = function(a) {
let b = []
let c = []
for (i = 0; i < a.length - 1; i++) {
b.push(mid(a[i], a[i + 1]))
c.push(a[i])
c.push(b[i])
}
c.push(a[a.length - 1])
return c
}
while (testarray.length < 30) {
var testarray = split(testarray)
}
var counter = 0
while (counter < testarray.length) {
seg(testarray[counter])
counter++
}
<svg id="svg1"></svg>
固定代码,谢谢!
问题是您在遍历列表时正在修改列表。别这样!:-)
创建一个从原始列表生成的第二个列表,然后返回第二个列表。或者,您可以尝试以相反的顺序进行迭代,但这使您依赖于拼接语义-这仍然是一种危险的做法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句