【问题标题】:How to split an array in half and swap the second parts of elements with first part of elements如何将数组分成两半并将元素的第二部分与元素的第一部分交换
【发布时间】:2022-01-22 19:46:36
【问题描述】:

可能在 javascript 中使用循环而不是方法

这里是我的练习规格:

编写一个名为Swapper()的函数 将输入作为参数的数组 并且,在交换前半部分和后半部分之后,将修改后的数组返回给调用者。 示例

input: [5, 11, 1, 44, 2, 43]
output: [44, 2, 43, 5, 11, 1]

如果数组长度为奇数,则中心值必须保持不变。

【问题讨论】:

  • 请向我们展示您的尝试,并正确解释问题所在,分别。其中哪一部分是您自己无法实现的。

标签: javascript arrays function loops


【解决方案1】:
You can use array.splice method to split an array in half and store the result in a temporary variavble and than use spread operator to combine both the arrays into a single one.
    
    let a = [1,2,3,4,5,6];
    let temp = a.splice(0,a.length/2);
    let splitted = [...a , ...temp];
    console.log(splitted)

【讨论】:

    【解决方案2】:

    看看这个

    const sample = [5, 11, 1, 44, 43, 46];
    var split=0, arr, arr1, arr2;
    
    if(sample.length%2==0) split = sample.length / 2;
    else split = (sample.length - 1)/2;
    
    arr1 = sample.slice(0,split);
    if(sample.length%2==0){
       arr2 = sample.slice(split, sample.length);
       arr = [arr2,arr1];
    }
    else{
       arr2 = sample.slice(split+1, sample.length);
       arr = [arr2,sample[split],arr1];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2018-03-09
      • 2023-03-03
      • 2022-11-16
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多