来自eloquent javascript listTo Array的练习:为什么不是全局列表null的值

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

为什么列表的价值在全球范围内保持不变?不应该是空的吗?

let list = {value: 1, rest: { value: 2, rest: null}};

function listToArray(list){
    let array = [];
    while( list != null)
    {
        array.push(list.value);
        list = list.rest;
    }
    return array;
}

为什么全局array1在通过下面的函数后改变了,如果函数中的局部变量数组用于引用它?

let array1 = [1,2,3];

function reverseArrayInPlace(array){

for(let i = 0; i <Math.floor(array.length / 2); i ++){

  let temp = array[i];

  array[i] = array[array.length - i - 1];

  array[array.length - i - 1] = temp;

}

}

javascript
1个回答
0
投票

具有值和rest的变量列表对象与函数中使用的参数列表不同。如果我删除参数,你会得到你所期望的。

let list = {value: 1, rest: { value: 2, rest: null}};

function listToArray () {
  let array = [];
  while( list != null)
  {
    array.push(list.value);
    list = list.rest;
  }
  return array;
}

let array = listToArray();

console.log( 'list : ', list );

这是你的第二个例子:

let array1 = [1,2,3];

function reverseArrayInPlace (array) {
  
  // Here array is pointing to array1
  
  for(let i = 0; i < Math.floor(array.length/2); i++){
   
    let temp = array[i];
    
    // What is happening here is that you are modifying directly whats in array
    // by affecting something to an index of it => array[ i ].
    // Since array is pointing on array1, array1 is getting modified
    array[i] = array[array.length - i - 1];

    array[array.length - i - 1] = temp;
    
  }

}

reverseArrayInPlace ( array1 );

console.log( array1 );

如果我在做任何事之前使用slice,array1将保持不变:

let array1 = [1,2,3];

function reverseArray ( array ) {
  
  // array.slice() is used to copy the array, array is now pointing to a copy of array1
  array = array.slice();
  
  for(let i = 0; i < Math.floor(array.length/2); i++){
   
    let temp = array[i];
    
    // Since array is now a copy of array, it is not modifying the original one
    array[i] = array[array.length - i - 1];

    array[array.length - i - 1] = temp;
    
  }

}

reverseArray ( array1 );

console.log( array1 );
© www.soinside.com 2019 - 2024. All rights reserved.