gpt4 book ai didi

javascript - 迭代矩形的周长

转载 作者:行者123 更新时间:2023-11-30 08:27:53 24 4
gpt4 key购买 nike

假设您有一个矩形,width=10, height=20 并且想要获取周边每个像素的坐标。您本可以使用 4 个 for 循环完成它,但是没有更好、更简洁的方法吗?

for(x=0; x<width; x++){
doSomethingWith(x,0)
}
for(y=0; y<height; y++){
doSomethingWith(0,y)
}
for(x=1; x<width; x++){
doSomethingWith(x,height)
}
for(y=1; y<height; y++){
doSomethingWith(width,y)
}

我将使用 javascript,但欢迎提供伪代码或其他语言的帮助。

image of rectangle with colored perimiter

最佳答案

你可以只用两个 for 循环来完成:

for (x = 0; x < width; x++) {
doSomethingWith(x, 0)
doSomethingWith(x, height - 1)
}
for (y = 0; y < height; y++) {
doSomethingWith(0, y)
doSomethingWith(width - 1, y)
}

例子:

var x, y, width = 10, height = 20;
for (x = 0; x < width; x++) {
doSomethingWith(x, 0)
doSomethingWith(x, height - 1)
}
for (y = 0; y < height; y++) {
doSomethingWith(0, y)
doSomethingWith(width - 1, y)
}
function doSomethingWith(x, y) {
var b = document.createElement("div");
b.className = "block";
b.style.left = (x * 10) + "px";
b.style.top = (y * 10) + "px";
document.body.appendChild(b)
}
.block {
box-sizing: border-box;
position: absolute;
width: 10px;
height: 10px;
background-color: red;
border: 1px solid black;
}

关于javascript - 迭代矩形的周长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395696/

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