gpt4 book ai didi

javascript - 创建一个函数以将整数数组旋转给定的步数

转载 作者:行者123 更新时间:2023-11-28 12:16:30 26 4
gpt4 key购买 nike

所以我做了一件事:

function rotate(array, [steps]){
var array_length = array.length;
var real_steps = 1;
var new_array = [];
if (typeof steps !== 'undefined')
{
real_steps = steps;
}
else
{
steps = 1;
}

if (real_steps > array_length)
{
real_Steps = steps % array_length;
}
else if (real_steps < 0)
{
if (real_steps % 2)
{
real_steps = real_steps*(-1)+2;
}
else
{
real_steps = real_steps*(-1);
}
real_steps = steps % array_length;
}

else if (real_steps === 0)
{
return array;
}
for(var i=0; i<=array_length-real_steps; i++)
new_array[i] = array[i+real_steps];
for(var i=array_length-real_steps; i<array_length-real_steps;i++)
new_array[i] = array[i];
return new_array
}

该函数的目的是获取整数数组并将整数移动给定的步数。如果未定义,则步骤默认为 1。

我在测试程序时遇到了麻烦,就像简单地拍打

var a = [1, 2, 3, 4];
rotate(a);

不起作用。代码本身有一个问题,我认为是由未定义的 [steps] 引发异常引起的,但如果无法自己测试,我无法确定问题是什么。

如何测试函数的输出?

更详细地说,现阶段我的功能是否存在任何明显的问题?

最佳答案

函数中的一些问题:

  • 可选 step 参数的语法不是 [step],而只是 step:在 JavaScript 中,所有参数都是可选的。不过,您可以在参数列表中使用 step = 1 指定默认值。

  • 模 2 (%2) 很奇怪:我不明白这对处理负步有何帮助。您可以使用以下公式处理所有步骤值:

    steps - Math.floor(steps / array.length) * array.length
  • 有很多代码可以通过 sliceconcat 轻松完成

  • 您没有提供读取函数返回值的代码。函数不改变原始数组是一种很好的做法(因此请保持这种方式),但也许您希望通过 rotate(a) 修改 a ?无论如何,结果由函数返回,因此您可以直接输出该结果或将其存储在变量中。

代码:

function rotate(array, steps = 1){ // Optional argument notation is not []
steps = steps - Math.floor(steps / array.length) * array.length; // works also OK for negative
return array.slice(steps).concat(array.slice(0, steps));
}

// Demo
var a = [1,2,3,4,5];
for (var step = -6; step < 7; step++) {
console.log('step ' + step + ' => ' + rotate(a, step));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

具有就地旋转的版本

如果您需要函数改变数组,请使用splice:

function rotate(array, steps = 1){ // Optional argument notation is not []
steps = steps - Math.floor(steps / array.length) * array.length; // works also OK for negative
array.push(...array.splice(0, steps));
}

// Demo
for (var step = -6; step < 7; step++) {
var a = [1,2,3,4,5]; // reset
rotate(a, step);
console.log('step ' + step + ' => ' + a);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 创建一个函数以将整数数组旋转给定的步数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599392/

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