2

有人可以解释以下代码片段的输出行为吗?

function Vertex(x, y, z) {
    this.x = parseInt(x);
    this.y = parseInt(y);
    this.z = parseInt(z);
};

var set = {};

var v1 = new Vertex(1,2,3);
var v2 = new Vertex(2,3,4);
var v3 = new Vertex(1,2,3);
var v4 = new Vertex(4,5,6);

set[v1] = 10;
set[v2] = 11;


alert(set[v1] + " " + set[v2] + " " + set[v3] + " " + set[v4]);
// Output: 11 11 11 11
4

2 回答 2

3

对象属性是字符串,因此如果您尝试这样做set[v1] = 10;,v1将被转换为字符串(字符串将为[object Object]),因此基本上您会得到set['[object Object]'] = 10;所有对象都会发生这种情况,并且您设置的每个值都将覆盖前一个值。

所以你的代码相当于这个

function Vertex(x, y, z) {
    this.x = parseInt(x);
    this.y = parseInt(y);
    this.z = parseInt(z);
};

var set = {};

var v1 = new Vertex(1,2,3);
var v2 = new Vertex(2,3,4);
var v3 = new Vertex(1,2,3);
var v4 = new Vertex(4,5,6);

set['[object Object]'] = 10;
set['[object Object]'] = 11;          

alert(set['[object Object]'] + " " + set['[object Object]'] + " " + set['[object Object]'] + " " + set['[object Object]']);
// Output: 11 11 11 11
于 2012-10-10T19:12:02.707 回答
1
v1 == v2 == v3 == v4 == "[object Object]" when expressed as a string

您不能将对象作为键。

set[v1] is the same as set["[object Object]"]

这就是为什么您要获得所有 4 个键的最后一个值的原因。

这是您对代码进行了重新设计以按预期执行

var object_id = 0; /* global object instance id */
function Vertex(x, y, z) {
    this.x = parseInt(x);
    this.y = parseInt(y);
    this.z = parseInt(z);
    this.id = (object_id++); /* add id to object */
};
/* override to string so it can be used as a key */
Vertex.prototype.toString = function() {
    return JSON.stringify(this);
}

var set = {};

var v1 = new Vertex(1,2,3);
var v2 = new Vertex(2,3,4);
var v3 = new Vertex(1,2,3);
var v4 = new Vertex(4,5,6);

set[v1] = 10;
set[v2] = 11;


alert(set[v1] + " " + set[v2] + " " + set[v3] + " " + set[v4]);
于 2012-10-10T19:12:48.403 回答