雄辩的JavaScript练习4.2反转数组

eloquent javascript exercise 4.2 reversing an Array

本文关键字:数组 练习 JavaScript      更新时间:2023-09-26

在下面的代码中,我不明白为什么 reverseArrayOne 与 reverseArrayTwo 相比不返回反向数组。从本质上讲,我相信我在这两种情况下都将反向数组分配给数组。链接到问题 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]

请记住,处理方式和对象与值、变量和文字值之间的区别不同。我添加了解释程序的评论,如果您需要更多详细信息,请增加答案。

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

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]

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

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)
我认为

这可能是一个好方法......

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;
}