亲宝软件园·资讯

展开

js数组互转

~疆 人气:0

一维数组转二维数组

 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);

加载全部内容

相关教程
猜你喜欢
用户评论