【问题标题】:How to fix my code and get reversed order of first and last number in array如何修复我的代码并获得数组中第一个和最后一个数字的相反顺序
【发布时间】:2019-12-13 01:42:16
【问题描述】:

我正在编写代码,将数组中第一个和最后一个元素的顺序颠倒,而不使用任何函数。

我已经尝试过这样的示例代码,但我没有正确的输出。我要做的就是改变数组中第一个和最后一个键的位置,第一个是最后一个,最后一个是第一个,不使用任何函数,只是纯逻辑。

示例代码

var nums = [1,2,3,4,5,6,7,8,9,10];
var totalNums = [];

for(var i = 0; i < nums.length; i++) {
    console.log(nums[i]);

    totalNums = nums[0];
    nums[0] = nums[i - 1];
    totalNums = nums[0];
}

【问题讨论】:

  • 什么是nums
  • Nums 是数组的名称

标签: javascript arrays


【解决方案1】:

获取array[0]array[array.length-1] 并交换它们。

var temp = array[0];
array[0] = array[array.length-1];
array[array.length-1] = temp;

【讨论】:

  • 如何使用 for 循环获得该结果?有什么办法吗?
  • 完全没有必要。您将第一次保存,跳过中间项目,然后在到达最后一项时执行交换。
  • 是的,你完全正确。但我在想是否有办法用 for 循环做到这一点,我怎么能做到这一点.. 我已经尝试了一些东西,但我从来没有接近解决方案
【解决方案2】:

如果您的数组至少有两个项目( array.length &gt; 1),您可以交换它们。

let array = ['a', 'b', 'c', 'd', 'e', 'f'];
if (array.length > 1) {
  let first = array[0];
  let last = array[array.length - 1];
  array[0] = last;
  array[array.length - 1] = first;
}
console.log(array);

【讨论】:

    【解决方案3】:
    const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    const temp = nums[0]
    nums[0] = nums[nums.length-1]
    nums[nums.length-1] = temp
    

    结果:[9, 2, 3, 4, 5, 6, 7, 8, 1]

    【讨论】:

      【解决方案4】:

      您可以使用这个简短的 sn-p 交换元素:

      const nums = [1, 2, 3];
      
      // swap first and last elements
      [nums[0], nums[nums.length - 1]] = [nums[nums.length - 1], nums[0]];
      
      console.log(nums);

      【讨论】:

        【解决方案5】:

        如果nums 数组中的值只是数字,那么您可以在没有任何额外变量的情况下进行排列:

        const nums = [1, 2, 3, 4, 5];
        
        nums[0] = nums[0] + nums[nums.length - 1];
        nums[nums.length - 1] = nums[0] - nums[nums.length - 1];
        nums[0] = nums[0] - nums[nums.length - 1];
        
        console.log(nums); /** output: [5, 2, 3, 4, 1] **/

        如果值可能包含非数字值,则使用临时变量:

        const nums = [1, 2, 3, 4, 5];
        
        let aux = nums[0];
        
        nums[0] = nums[nums.length - 1];
        nums[nums.length - 1] = aux;
        
        console.log(nums); /** output: [5, 2, 3, 4, 1] **/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-08
          • 2019-08-26
          • 1970-01-01
          • 2021-05-26
          相关资源
          最近更新 更多