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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742315946a4420840.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信