【问题标题】:conditional in for loop misbehaving [duplicate]有条件的for循环行为不端[重复]
【发布时间】: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


    【解决方案1】:

    currentPosition 是一个对象。当您对其进行更改时(例如currentPosition.x += 1),您总是在更改同一个对象。

    然后你将它推入一个数组,但你实际上推的是一个对该对象的引用,所以数组的所有元素都指向同一个底层对象。

    要修复您的代码,您需要在将对象信息推送到数组时将其克隆到一个新对象中:

    housesVisited.push({x: currentPosition.x, y: currentPosition.y});
    

    【讨论】:

    • 非常感谢!是的,没看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    相关资源
    最近更新 更多