雄辩的javascript练习4.2倒转一个数组

时间:2014-12-11 21:33:03

标签: javascript arrays arguments global-variables scoping

在下面的代码中,我不明白为什么 reverseArrayOne reverseArrayTwo 相比不会返回反向数组。本质上我相信我在两种情况下都将 reversedArray 分配给数组。链接到问题http://eloquentjavascript.net/04_data.html#c_F3JsLaIs+m

function reverseArray(array) {
reversedArray = [];
  for (i=array.length-1; i>=0; i--) {
    reversedArray.push(array[i]);
  }
  return reversedArray;
}

function reverseArrayOne(array) {
  array = reverseArray(array);
  return array;
}

function reverseArrayTwo(array) {
  reversedArray = reverseArray (array);
  for (i=0; i<reversedArray.length; i++) {
    array[i] = reversedArray[i];
  }
  return array;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayOne(arrayValue);
console.log(arrayValue);
// → [1,2,3,4,5]
reverseArrayTwo(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]

3 个答案:

答案 0 :(得分:0)

将数组传递给函数时,该函数可能会更改数组本身的值。

reverseArrayOne(arrayValue)返回反向数组,但不会更改arrayValue的值。

reverseArrayTwo(arrayValue)实际上会更改arrayValue的值,因为函数中的这一行:

array[i] = reversedArray[i];

在日志中,您显示的是arrayValue的值,而不是函数的返回结果

console.log(arrayValue)

第一个函数不会更改数组值,因此它将返回[1,2,3,4,5]。第二个函数实际上改变了数组值,因此它将返回[5,4,3,2,1]。如果您只需要打印数组的反转,那么您应该

result = reverseArrayOne(arrayValue);
console.log(result)

答案 1 :(得分:0)

请注意,object的处理方式与values,variables and literals值之间的区别不同。我添加了解释程序的评论,如果您需要更多详细信息,请提出答案。

一个主要区别是: 对象通过引用传递,后者按值传递

function reverseArray(array) {
reversedArray = [];
  for (i=array.length-1; i>=0; i--) {
    reversedArray.push(array[i]);
  }
//return a new array with elements in a reverse order of original array
  return reversedArray;
}

function reverseArrayOne(array) {
//scope of object reference is in the function only and hence is not reflected outside
  array = reverseArray(array);
//return the same object pointer which now points to a new array
  return array;
}

function reverseArrayTwo(array) {
      reversedArray = reverseArray (array);
      for (i=0; i<reversedArray.length; i++) {
//you are changing the properties of the same object(this is different from merely changing the reference of the object)
        array[i] = reversedArray[i];
      }
      return array;
    }
    var arrayValue = [1, 2, 3, 4, 5];
//passing arrayValue as reference
    reverseArrayOne(arrayValue);
//original arrayValue still points to the original array since the reverse value is not in scope.
    console.log(arrayValue);
    // → [1,2,3,4,5]
    reverseArrayTwo(arrayValue);
//the original array is the same,but the internal property of the object has been changed and hence is reflected
    console.log(arrayValue);
    // → [5, 4, 3, 2, 1]

答案 2 :(得分:0)

我认为这可能是一个好方法...

var list = ["orange", "apple", "pear"]
var newList = [];

function newReverse(list){
  for(var i=0; i<list.length; i++){
    newList.push(list[i]);
  }
  newList.reverse();
  return newList;
}