0
点赞
收藏
分享

微信扫一扫

js 合并、复制和修改定型数组

定型数组同样使用数组缓冲来存储数据,而数组缓冲无法调整大小。因此,下列方法不适用于定型 数组:

  • concat()
  • pop()
  • push()
  • shift()
  • splice()
  • unshift()

不过,定型数组也提供了两个新方法,可以快速向外或向内复制数据:set()和 subarray()。

set()从提供的数组或定型数组中把值复制到当前定型数组中指定的索引位置:

// 创建长度为 8 的 int16 数组
const container = new Int16Array(8);
// 把定型数组复制为前 4 个值
// 偏移量默认为索引0 container.set(Int8Array.of(1, 2, 3, 4)); console.log(container); // [1,2,3,4,0,0,0,0] // 把普通数组复制为后 4 个值
// 偏移量 4 表示从索引 4 开始插入 container.set([5,6,7,8], 4); console.log(container); // [1,2,3,4,5,6,7,8]
// 溢出会抛出错误 container.set([5,6,7,8], 7); // RangeError

subarray()执行与 set()相反的操作,它会基于从原始定型数组中复制的值返回一个新定型数组。 复制值时的开始索引和结束索引是可选的:

const source = Int16Array.of(2, 4, 6, 8);
// 把整个数组复制为一个同类型的新数组
const fullCopy = source.subarray(); console.log(fullCopy); // [2, 4, 6, 8]
// 从索引 2 开始复制数组
const halfCopy = source.subarray(2); console.log(halfCopy); // [6, 8]
// 从索引1开始复制到索引3
const partialCopy = source.subarray(1, 3); console.log(partialCopy); // [4, 6]
定型数组没有原生的拼接能力,但使用定型数组 API 提供的很多工具可以手动构建:
// 第一个参数是应该返回的数组类型
// 其余参数是应该拼接在一起的定型数组
function typedArrayConcat(typedArrayConstructor, ...typedArrays) {
// 计算所有数组中包含的元素总数
const numElements = typedArrays.reduce((x,y) => (x.length || x) + y.length);
// 按照提供的类型创建一个数组,为所有元素留出空间
const resultArray = new typedArrayConstructor(numElements);
// 依次转移数组
let currentOffset = 0; typedArrays.map(x => {
        resultArray.set(x, currentOffset);
        currentOffset += x.length;
      });
      return resultArray;
    }
    const concatArray = typedArrayConcat(Int32Array,
                                         Int8Array.of(1, 2, 3),
                                         Int16Array.of(4, 5, 6),
                                         Float32Array.of(7, 8, 9));
    console.log(concatArray);  // [1, 2, 3, 4, 5, 6, 7, 8, 9]
    console.log(concatArray instanceof Int32Array); // true

举报

相关推荐

0 条评论