最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does splice exist for TypedArrays or is there an equivalent? - Stack Overflow

programmeradmin2浏览0评论

Is there or is there ever going to be an equivalent of Array.prototype.splice for TypedArrays?

I want to be able to delete a range of items from a TypedArray.

Is there or is there ever going to be an equivalent of Array.prototype.splice for TypedArrays?

I want to be able to delete a range of items from a TypedArray.

Share Improve this question edited Aug 26, 2015 at 18:29 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Aug 26, 2015 at 16:39 civiltomainciviltomain 1,1661 gold badge9 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

So TypedArrays in ES6 are not classical Javascript arrays, but closer to an API for a underlying binary buffer (https://developer.mozilla/en-US/docs/Web/JavaScript/Typed_arrays).

Since splice mutates the actual length of array it isn't usable with TypedArrays (http://www.es6fiddle/idt0ugqo/).

You can create similar behavior by creating your own splice (although it will be slower).

This is a simple equivalent except that it doesn't account for all nuances of `splice. As @bergi mented, I don't allow negative values.

function splice(arr, starting, deleteCount, elements) {
  if (arguments.length === 1) {
    return arr;
  }
  starting = Math.max(starting, 0);
  deleteCount = Math.max(deleteCount, 0);
  elements = elements || [];


  const newSize = arr.length - deleteCount + elements.length;
  const splicedArray = new arr.constructor(newSize);

  splicedArray.set(arr.subarray(0, starting));
  splicedArray.set(elements, starting);
  splicedArray.set(arr.subarray(starting + deleteCount), starting + elements.length);
  return splicedArray;
};

splice(new Uint8Array([1,2,3]), 0, 1); // returns Uint8Array([1,3])

http://www.es6fiddle/idt3epy2/

Is there or is there ever going to be an equivalent of Array.prototype.splice for TypedArrays?

No, because TypedArrays cannot change their size. There's no push/pop/shift/unshift methods either.

If you want to delete elements from your array, you typically set them to null, and care for those nulls when traversing the array. This also avoids having to shift around all elements after the ones being deleted.

If you really need this, your best bet is to create a new array and copy elements over it (the ones before the deleted section, the new ones, and then the ones after the deleted section). @cdbitesky has given a nice implementation for this.

发布评论

评论列表(0)

  1. 暂无评论