【发布时间】:2016-03-24 02:16:05
【问题描述】:
我认为它应该很简单,但不知何故,我不明白我做错了什么。
我有这个代码:
var currentPosition = {
x:10000,
y:10000
};
var directions = "v>v<";
var housesVisited = [{x:10000, y:10000}];
function createHouseCoordinates(data){
for(var x = 0; x<4; x++){
if(data[x]=="^"){
currentPosition.x += 1;
} else if(data[x]=="v"){
currentPosition.x -= 1;
} else if(data[x]==">"){
currentPosition.y += 1;
} else if(data[x]=="<"){
currentPosition.y -= 1;
}
housesVisited.push(currentPosition);
}
}
createHouseCoordinates(directions);
console.log(housesVisited);
它应该以符号的形式获取方向,修改当前位置,并创建一个对象数组,列出所有访问过的位置。上面的结果,当我运行它时,给了我这个(基本上是结束位置):
[ { x: 10000, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 } ]
我期待:
[ { x: 10000, y: 10000 },
{ x: 9999, y: 10000 },
{ x: 9999, y: 10001 },
{ x: 9998, y: 10001 },
{ x: 9998, y: 10000 } ]
我做错了什么?我应该阅读什么才能更好地理解这一点..? 提前致谢!
【问题讨论】:
标签: javascript for-loop conditional