-2

Hi I was sorting an array with sort and don't know why/how/the order in which JavaScript is executing the code.

code below

arr = ["cc", "aa", "dd", "bb"];

console.log(arr);

fun = function() {
    var re = arr;
    console.log(re);

    re = re.sort();
    console.log(re); 
};


fun();

I know that the sort() method changes the original array object but why when I console.log before the sort method am I not getting the original order of the array?

Can someone please explain JavaScript's execution order? I thought it executed top to bottom.

Thanks.

update: JSfiddle below

http://jsfiddle.net/BPNWC/

4

2 回答 2

2

你的第一console.log张打印出来["cc", "aa", "dd", "bb"]

你的第二个console.log打印出来,["cc", "aa", "dd", "bb"] 因为没有任何改变

你的第三个console.log打印出来,[ 'aa', 'bb', 'cc', 'dd' ] 因为sort(); 将按字母顺序“排序”数组。

于 2013-10-31T09:22:11.397 回答
0

如果要检查 'Array.join' 方法的中间执行步骤,可以传递一个比较器并检查它收到的值:

arr.sort(function(a, b) {
    console.log([a, b], arr);             // log both parameters and the array
    return (a==b ? 0 : (a < b ? -1 : 1)); // return re comparison result
});
于 2013-10-31T09:39:14.153 回答