在javascript中,数组显示“按值传递”行为,而不是“按引用传递”

问题描述 投票:0回答:1

我知道数组是javascript中的对象,使其成为非原始数据类型,默认情况下使其成为按引用传递。现在,在我遇到的大多数用例中,这都是事实,但是我共享的代码显示了一个我不理解的怪异行为,似乎更像是“按值传递类型”。

var arr = ['a','b','c']
/*
function addArr(ar){
    ar.push('d')
    return ar
}

console.log(addArr(arr))  // ['a', 'b', 'c', 'd']
console.log(arr)          // ['a', 'b', 'c', 'd']
*/

//the above output is expected behavior for an Array object



function changeArr(ar){

    console.log(ar)   //1-// ['a', 'b', 'c']
    ar = ['12','11']
    console.log(ar)   //2-// ['12', '11']
    return ar
}

console.log(changeArr(arr)) //3-// ['12', '11']
console.log(arr)            //4-// ['a', 'b', 'c']

//now I expect the forth console output to be  ['12','11'] here because it is an object
javascript arrays pass-by-reference pass-by-value primitive-types
1个回答
0
投票
function changeArr(ar){

    console.log(ar)
    ar = ['12','11'] // <- THIS LINE RIGHT HERE
    console.log(ar)
    return ar
}

您正在创建一个新数组,而不是操纵旧数组。每次调用该函数时,您都在创建一个新数组。


0
投票

您基本上是重新评估对象,而不是修改原始对象。

ar = ['12','11']

这就是Javascript重新分配新值的原因。

© www.soinside.com 2019 - 2024. All rights reserved.