简体   繁体   中英

Working through Eloquent JavaScript exercise

Im studying the book "eloquent javascript" Im having trouble noting the rest of this excerise. Plus I dont understand why in the for loop "i' has to be half of array.length. You can see I'm trying to note every step to see exactly what it does.

any help would be appericated

//function named reverseArrayInPlace with one parameter array
function reverseArrayInPlace(array) {
  // foor loop, intialize i at 0, i less than half array length, i plus one 
  //for ever iteration of the loop
  for (let i = 0; i < Math.floor(array.length / 2); i++) {
    //let old (called old because we are going back to original)
    //equal array [current array item] we are on
    let old = array[i];
    // array [current item] equals..
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = old;
  }
  return array;
}

Don't you think this one is more "eloquent"? ;-)

 const reverseArrayInPlace = arr => { let len = arr.length, half = len >> 1 // integer division by 2; for (let x=0, y=--len; x < half; x++, y--) [ arr[x], arr[y] ] = [ arr[y], arr[x] ]; // swap array values in ES7 } let myArr_A = [1,2,3,4,5,6,7,8,9,0 ], myArr_B = [1,2,3,4,5,6,7,8,9 ], myArr_C = ['one']; reverseArrayInPlace( myArr_A ) reverseArrayInPlace( myArr_B ) reverseArrayInPlace( myArr_C ) console.log(JSON.stringify(myArr_A)) console.log(JSON.stringify(myArr_B)) console.log(JSON.stringify(myArr_C))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM