调用JavaScript函数会改变参数的值.为什么?

Got*_*ied 2 javascript

我在使用JavaScript方面遇到了一些麻烦.当我在下面的"LINE 2"中调用函数compare时,它会更改to_sort [i]的值,但不会更改pivot的值.在'LINE 1'打印的值与'LINE 3'不同.为什么是这样?

我认为这可能与pivot和to_sort [i]通过引用传递有关,但显然原始类型是通过JavaScript中的值传递的.

帮助赞赏.

function compare(str1, str2){
    for (i = 0;i < Math.min(str1.length,str2.length); ++i){
        if(str2[i] < str1[i]){
            return false;
        }
    }
    if(str1.length != str2.length && str2.length < str1.length){
        return false;   
    }
    return true;

}

function quicksort(to_sort){
    if(to_sort.length < 2) return to_sort;
    var pivot = to_sort[0];
    var less_pivot = [];
    var more_pivot = [];
    for(i = 1; i < to_sort.length; ++i){
        console.log(to_sort[i]);// LINE 1
        if(compare(to_sort[i], pivot)){//LINE 2
            console.log(to_sort[i]); //LINE 3
            less_pivot = less_pivot.concat(to_sort[i]);
        }
        else{
            more_pivot = more_pivot.concat(to_sort[i]);
        }
    }
    return [].concat(quicksort(less_pivot, compare_function), pivot, quicksort(more_pivot, compare_function));
}
quicksort(["2.0.1", "2.0.0"]);

output:
2.0.0
undefined
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 6

看起来它发生是因为compare函数改变了迭代索引的值i:

for (i = 0; i < Math.min(str1.length, str2.length); ++i) {
    if (str2[i] < str1[i]) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

因为你声明i没有var关键字.请记住,将未声明的变量赋值为全局变量.