简体   繁体   English

对象JavaScript中的奇怪行为数组

[英]Strange behavior array in object JavaScript

Why b.first[0] return "t" and how I can avoid this? 为什么b.first [0]返回“ t”,如何避免这种情况?

I need safe "q" in b.first[0] 我在b.first [0]中需要安全的“ q”

var extend = function(o,p){
    for(prop in p){
        o[prop] = p[prop];
    }
    return o;
};

var a = {first:['q','w']};
var b = {};

extend(b,a);

document.write(a.first[0]); //q
document.write(b.first[0]); //q

a.first[0] = 't';

document.write(a.first[0]); // t
document.write(b.first[0]); // t ?????????????????????

This is an issue relating to the concept that extending b by a doesn't recreate the data from a. 这是一个与将b扩展a不会从a重新创建数据的概念有关的问题。 If some of the data is an object (like an Array), it instead just "points" to that array instead of creating a new, identical array. 如果某些数据是对象(例如Array),那么它只是“指向”该数组,而不是创建一个新的相同数组。 Essentially you're storing two pointers to the same array, so when you change one, you change the other. 本质上,您将存储两个指向同一数组的指针,因此,当您更改一个指针时,您将更改另一个指针。

Here is a answer which discusses the idea of "cloning" an object in Javascript in more detail. 这是一个答案,更详细地讨论了“克隆” Javascript对象的想法。

https://stackoverflow.com/a/728694/1570248 https://stackoverflow.com/a/728694/1570248

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM