JavaScript:将对象存储在数组中

时间:2015-07-07 12:22:42

标签: javascript arrays object

请解释以下示例的结果,尤其是案例1.2和2.2:

不应该是案例1.2的输出:Object[0] {foo:"a"}
不应该是案例2.2的输出:Object[0] {foo:"b"}

var obj = {foo:'a'};    // Define an object
var arr = [obj];        // Store the object within an array
console.log(obj);       // Case 1.1: Object {foo:"a"}
console.log(arr);       // Case 1.2: Object[0] {foo:"c"}

function Foo(o){ o.foo = 'b'; };
Foo(obj);               // Change the object's property by using a function
console.log(obj);       // Case 2.1: Object {foo:"b"}
console.log(arr);       // Case 2.2: Object[0] {foo:"c"}

arr[0].foo = 'c';       // Change the object's property by using the array
console.log(obj);       // Case 3.1: Object {foo:"c"}
console.log(arr);       // Case 3.2: Object[0] {foo:"c"}

0 个答案:

没有答案