對於TypedArrays,是否存在或會有相應的Array.prototype.splice
?TypedArrays是否存在拼接或者是否存在相同的拼接?
我希望能夠從TypedArray刪除某個範圍內的項目。
對於TypedArrays,是否存在或會有相應的Array.prototype.splice
?TypedArrays是否存在拼接或者是否存在相同的拼接?
我希望能夠從TypedArray刪除某個範圍內的項目。
所以在ES6 TypedArrays不是經典的Javascript數組,但是更接近於API用於底層二進制緩衝液(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)。
由於splice
突變了陣列的實際長度,因此TypedArrays(http://www.es6fiddle.net/idt0ugqo/)不可用。
您可以通過創建自己的拼接(雖然會慢一些)建立類似的行爲。
這是一個簡單的等同,只是它不佔拼接的'所有的細微差別。正如@bergi所評論的,我不允許使用負值。
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])
是否有或有過將會是
Array.prototype.splice
爲TypedArrays
等效?
不,因爲TypedArrays
不能更改它們的大小。也沒有push
/pop
/shift
/unshift
方法。
如果你想刪除你的數組元素,您通常將它們遍歷數組時爲空,並照顧那些空值。這也避免了在被刪除之後不得不移動所有元素。
如果你真的需要這一點,最好的辦法是創建一個新的數組(已刪除的分區後,已刪除的部分以前生產的,在新的,然後的)複製了它的元素。 @cdbitesky爲此提供了一個很好的實現。
你是什麼意思「*保留空白*」? – Bergi
順便說一句,如果你想更貼近地模擬['Array :: splice'](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.splice),你應該關心對於負指數(從最後算起)並使用'elements = slice.call(arguments,3)' – Bergi
嗯,不,你不能。你可以通過傳入參數來插入'undefined' /'null'值,但是你不能插入漏洞 - 你需要''刪除''。你的例子產生'[1,null,3]',也許你的控制檯有問題。 – Bergi