How do I pass the value instead of the reference of an array?

javascript object

8004 просмотра

3 ответа

4279 Репутация автора

I have this structure:

var a = [];
a.push({"level": 1, "column": 4, "parent": "none", "title": "Node 0", "content": "Parintele suprem", "show": "1"});
var b = a;

a.push({"level": 1, "column": 5, "parent": "none", "title": "Node 1", "content": "Parintele suprem", "show": "1"});

console.log(b);

Now the problem is that b has the exact content as a (the content after the second push). This suggest (correct me if I'm wrong) that when I said b = a I actually gave b same reference as a, so whatever I do in a I have in b. The thing is that I need to pass the value. So I have the previews a, value in b.

Edit to make the question more clear: How do I pass the value instead of the reference?

Автор: zozo Источник Размещён: 08.02.2012 09:22

Ответы (3)


15 плюса

8089 Репутация автора

Решение

I think you can use this to copy the value instead of the reference:

var b = a.slice(0);  

EDIT
As the comments have mentioned and it's also mentioned here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

  • For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

  • For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

If a new element is added to either array, the other array is not affected.

Автор: Niklas Размещён: 08.02.2012 09:28

3 плюса

9940 Репутация автора

Yes, that's the way reference assignment works in javascript. You want to clone the object to make a copy, which is unfortunately more involved than it should be. Frameworks like MooTools provide the simplest solution, or you can roll your own clone function.

Автор: Rob Agar Размещён: 08.02.2012 09:29

7 плюса

71 Репутация автора

you can implement a clone method as follow:

function clone(source) {
    var result = source, i, len;
    if (!source
        || source instanceof Number
        || source instanceof String
        || source instanceof Boolean) {
        return result;
    } else if (Object.prototype.toString.call(source).slice(8,-1) === 'Array') {
        result = [];
        var resultLen = 0;
        for (i = 0, len = source.length; i < len; i++) {
            result[resultLen++] = clone(source[i]);
        }
    } else if (typeof source == 'object') {
        result = {};
        for (i in source) {
            if (source.hasOwnProperty(i)) {
                result[i] = clone(source[i]);
            }
        }
    }
    return result;
};

then:

var b = clone(a);

if you are sure that a is Array, only use Niklas's:

var b = a.slice();

ps: my english is poor:)

Автор: subei Размещён: 08.02.2012 09:45
Вопросы из категории :
32x32