JSON损坏的属性

JSON corrupted attributes

本文关键字:属性 损坏 JSON      更新时间:2023-09-26

我很难理解Javascript的行为。

代码:

function getPosition(element){
    var position = {
        x:$(".line div").has(element).index(),
        y:$(".line").has(element).index()
    };
    console.log(position.y);
    console.log(position)
    return position;
}

现在,当从函数调用它时,我得到的结果如下:

0
Object
x: 8
y: 3

我不明白的是,当试图通过对象引用而不是直接访问对象时,怎么可能更改对象属性。

但当我从控制台调用相同的函数时,我得到的是:

0
Object
x: 8
y: 0

这是传递给函数的相同元素。当X或Y为0(零)时,它似乎总是失败,当它是另一个数字时,它是可以的

有人能解释一下我做错了什么吗?或者是某种JS错误?无

编辑:

所以我终于发现问题出在哪里了。我一直认为我在传递价值观,但不幸的是,我一直都错了。在stackoverflow上的一些搜索中,我发现了关于JS值和引用的主题。

如果有人感兴趣又懒得读这个话题,你可以看看这个例子。这几乎是不言自明的。

function test(){
    var a = 5;
    var b = a; //b now has value of 5
    console.log("a:"+a+":b:"+b);
    b = 4;//a still has value of 5 and b is assinged to 4
    console.log("a:"+a+":b:"+b);
    var c = {val:1};
    var d = c; //d now has reference to c
    d.val = 2; //c.val changes because it is a reference
    console.log(c);
}

第2版:哦,顺便问一下,我怎么能把我的问题标记为已回答?

console.log延迟将值转换为字符串,直到应用程序速度减慢,这样日志记录就不会不必要地减慢应用程序的速度。

如果console.log(position)显示的值与调用console.log时的值不同,则是因为position在调用和控制台小部件决定格式化该值以供显示之间已被修改。

您可以通过尝试以下HTML来看到这一点:

<script>
// Emits the JSON form when converted to a string.
var obj = {
  x: 1,
  toString: function () {
    return JSON.stringify(this);
  }
};
console.log(obj);  // Often {x:2}
console.log("" + obj);  // Reliably {x:1}  
obj.x = 2;
</script>

寻找类似的代码

obj = getPosition(...);
...
obj.y = <expression that evaluates to zero>

或者,您可以通过更改来强制进行急切的格式化

 console.log(position)

 console.log("" + position)

所以我终于发现了问题所在。我一直认为我在传递价值观,但不幸的是,我一直都错了。在stackoverflow上的一些搜索中,我发现了关于JS值和引用的主题。

如果有人感兴趣又懒得读这个话题,你可以看看这个例子。这几乎是不言自明的。

function test(){
    var a = 5;
    var b = a; //b now has value of 5
    console.log("a:"+a+":b:"+b);
    b = 4;//a still has value of 5 and b is assinged to 4
    console.log("a:"+a+":b:"+b);
    var c = {val:1};
    var d = c; //d now has reference to c
    d.val = 2; //c.val changes because it is a reference
    console.log(c);
}