当前位置:主页 > 网页前端 > JavaScript代码 >

关于JS中一维数组和二维数组互转问题

时间:2023-02-01 10:28:45 | 栏目:JavaScript代码 | 点击:

一维数组转二维数组

 arr1to2(arr, number) {
      var arr2 = [];
      let len = arr.length;
      for (let i = 0, j = 0; i < len; i += number, j++) {
        arr2[j] = arr.splice(0, number);
      }
      return arr2;
    },

 使用:

let arr1 = [
      103.743896484375, 21.48374090716327, 101.05224609374999,
      20.550508894195637, 103.60107421874999, 17.518344187852218
    ];
    console.log('一维数组:', arr1);
    let arr2 = this.arr1to2(arr1, 2);
    console.log('二维数组:', arr2);

如果arr1to2第二个参数为3,效果如下:

 二维数组转一维数组

    //二维数组转一维数组
    let arr = [
      [103.743896484375, 21.48374090716327],
      [101.05224609374999, 20.550508894195637],
      [103.60107421874999, 17.518344187852218]
    ];
    console.log('二维数组:', arr);
    let newarr = [];
    for (const item of arr) {
      newarr = [...newarr, ...item];
    }
    console.log('一维数组:', newarr);

您可能感兴趣的文章:

相关文章