gpt4 book ai didi

reverseArrayInPlace 的 JavaScript 函数 -- Eloquent JavaScript Ch4

转载 作者:行者123 更新时间:2023-11-30 10:08:48 24 4
gpt4 key购买 nike

谁能告诉我这个函数在反转数组时哪里出错了?这是 Eloquent JavaScript 一书中的练习

我已经通过控制台检查了我的变量,循环似乎在工作,但最后数组索引似乎没有被覆盖,我不明白为什么!

我正在寻找的答案是:

var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]

"use strict";
var sampleArray = [1,3,5,7,9];

function reverseArrayInPlace (someArray) {
var MiddleIndex = (Math.floor(someArray.length/2));
for (var i = 0; i <= MiddleIndex-1; i++) {
var currentValue = someArray[i];
var mirrorIndex = someArray[someArray.length -i -1];
var temp = currentValue;
currentValue = mirrorIndex;
mirrorIndex = temp;
}

return someArray;
}

console.log(reverseArrayInPlace(sampleArray));

最佳答案

正如其他人已经注意到的那样,您忘记了赋值,因为 currentValue = mirrorIndex; 只是更改了 currentValue,而不是其中的元素数组本身。 temp 也是如此。更一般地说:您不能像这样将 Array 元素存储到变量中作为对该 Array 元素的 reference

它还会使您的函数看起来过于复杂。这里有两种选择。在第一个中,交换是通过存储一个值、替换元素并将存储的值分配给另一个元素来完成的。在第二行中,使用 Array.splice(参见 MDN)在一行中完成相同的操作。

Here is a test用于执行 3 个就地反向函数。

function reverseInPlace(arr) {
var len = arr.length-1, mid = Math.floor(len/2), i = -1;
while( i++ < mid ) {
var swap = arr[len-i]; // save swapvalue
arr[len-i] = arr[i]; // assign current value to swap position
arr[i] = swap; // assign swapvalue to current position
}
}

// Swapping in one line (using splice)
function reverseInPlace2(arr) {
var mid = Math.floor(arr.length/2), i = -1;
while( i++ < mid ) { arr[i] = arr.splice(-(i+1), 1, arr[i])[0]; }
}

// demo
var log = Helpers.log2Screen;
var arr = [1,2,3,4];
reverseInPlace(arr);
log( 'Even length: `reverseInPlace(arr) -&gt; [', arr, ']`' );

arr = [1,2,3,4,5,6,7];
reverseInPlace(arr);
log( 'Odd length: `reverseInPlace(arr) -&gt; [', arr, ']`' );

arr = [1,2,3,4,5];
reverseInPlace2(arr);
log( 'Use `Array.splice: reverseInPlace2(arr4) -&gt; [', arr, ']`' );

// clarification of what happens in your code
log('\n<b>Clarification of what happens in your code</b>');

var myArr = [1,2,3,4,5];
var el2 = myArr[2];

log('Assigned: `MyArr: ', myArr, ', el2: ', el2, '`');
log( 'Storing: `var el2 = myArr[2];`' );
el2 = myArr[0];
log( 'Assigning: `el2 = myArr[0];`' );
log( '`myArray` did not change `MyArr: ', myArr, '`' );
log( 'But `el2` did: ', '`el2: ', el2, '`' );
<!-- some helpers -->
<script src="https://rawgit.com/KooiInc/Helpers/master/Helpers-min.js"></script>

关于reverseArrayInPlace 的 JavaScript 函数 -- Eloquent JavaScript Ch4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27647032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com