最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Working with arrays passed byref - Stack Overflow

programmeradmin2浏览0评论

I would like for someone to explain this to me:

function myFunction(array){
    array = $.grep(array, function(n,i){return n > 1 });
}

var mainArray = [1,2,3];

myFunction(mainArray);
document.write(mainArray) // 1,2,3, but i'm expecting 2,3

but if i do something like

    array[3] = 4;

in place of the $.grep line, i get 1,2,3,4. Shouldn't mainArray bee the new array created by $.grep?

I would like for someone to explain this to me:

function myFunction(array){
    array = $.grep(array, function(n,i){return n > 1 });
}

var mainArray = [1,2,3];

myFunction(mainArray);
document.write(mainArray) // 1,2,3, but i'm expecting 2,3

but if i do something like

    array[3] = 4;

in place of the $.grep line, i get 1,2,3,4. Shouldn't mainArray bee the new array created by $.grep?

Share edited Apr 30, 2014 at 17:34 Jason asked Apr 23, 2010 at 2:20 JasonJason 52.6k38 gold badges138 silver badges186 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

No, the array parameter is also a local (reference) variable. The function assigns a new array to this variable, but that doesn't affect the caller's variables. All parameters (including references), are passed by value.

If you modified (mutated) the contents of array, that would be different:

function myFunction(array){
    var grepResult = $.grep(array, function(n,i){return n > 1 });
    array.length = 0;
    Array.prototype.push.apply(array, grepResult);
}

It is due the evaluation stretegy that JavaScript implements.

Your function receives a copy of the reference to the object, this reference copy is associated with the formal parameter and is its value, and an assignment of a new value to the argument inside the function does not affect object outside the function (the original reference).

This kind of evaluation strategy is used by many languages, and is known as call by sharing

发布评论

评论列表(0)

  1. 暂无评论