在 JavaScript 中,我有一个数组。我push()
用来添加数组元素,但是当我操作所述元素时,每个数组元素都会改变,而应该只有一个。我的代码是:
// Arrays to hold the elements that have been created (added to the document).
create.element_array = []
create.element_array["name"] = []
create.element_array["name"]["properties"] = []
var element_properties =
{
// Default all to 0.
borderTopStyle: 0, borderRightStyle: 0, borderBottomStyle: 0, borderLeftStyle: 0,
borderTopWidth: 0, borderRightWidth: 0, borderBottomWidth: 0, borderLeftWidth: 0,
borderTopColor: 0, borderRightColor: 0, borderBottomColor: 0, borderLeftColor: 0,
}
// Testing purposes. These will be added dynamically in production version.
create.element_array["name"].push("default_header");
create.element_array["name"]["properties"].push(element_properties);
create.element_array["name"].push("default_body");
create.element_array["name"]["properties"].push(element_properties);
create.element_array["name"].push("default_footer");
create.element_array["name"]["properties"].push(element_properties);
// Evidence that each array element is changed with index manipulation.
create.element_array["name"]["properties"][0].borderTopStyle = "dashed";
console.log(create.element_array["name"]["properties"][0]);
console.log(create.element_array["name"]["properties"][1]);
console.log(create.element_array["name"]["properties"][2]);
我期望的结果是只应更改索引 0,但事实并非如此。上面的 console.log 行将输出以下内容:
Object
borderBottomColor: 0
borderBottomStyle: 0
borderBottomWidth: 0
borderLeftColor: 0
borderLeftStyle: 0
borderLeftWidth: 0
borderRightColor: 0
borderRightStyle: 0
borderRightWidth: 0
borderTopColor: 0
borderTopStyle: "dashed"
borderTopWidth: 0
__proto__: Object
library.js:8
Object
borderBottomColor: 0
borderBottomStyle: 0
borderBottomWidth: 0
borderLeftColor: 0
borderLeftStyle: 0
borderLeftWidth: 0
borderRightColor: 0
borderRightStyle: 0
borderRightWidth: 0
borderTopColor: 0
borderTopStyle: "dashed"
borderTopWidth: 0
__proto__: Object
library.js:8
Object
borderBottomColor: 0
borderBottomStyle: 0
borderBottomWidth: 0
borderLeftColor: 0
borderLeftStyle: 0
borderLeftWidth: 0
borderRightColor: 0
borderRightStyle: 0
borderRightWidth: 0
borderTopColor: 0
borderTopStyle: "dashed"
borderTopWidth: 0
__proto__: Object
library.js:8
borderTopStyle
当我明确地将索引 0 定义为唯一被更改的索引时,为什么要为每个元素更改?