2

For some reason, I can't get .slice() to work with a Float32Array. If you replace Float32Array by Array, it works perfectly fine. The doc for Float32Array lists .slice() as a method, so I don't understand if there's a bug or something? Or is it 2:00 AM and I can't see something obvious?

function test()
{
    var buf = new Float32Array( 10 );
    for (var i = 0; i < 10; i++) {
        buf[i] = i*0.3;

    }
    var test = buf.slice(2,5);
    alert("Hello, Coding Ground!" + test[0]);
}
test();
user3180077
  • 633
  • 1
  • 8
  • 16

3 Answers3

2

Check How to convert a JavaScript Typed Array into a JavaScript Array

function test()
{
    var buf = new Float32Array( 10 );
    var array =  Array.prototype.slice.call(buf);
    for (var i = 0; i < 10; i++) {
        array[i] = i*0.3;

    }
    var test = array.slice(2,5);
    alert("Hello, Coding Ground!" + test[0]);
}
test();
Community
  • 1
  • 1
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice

Looks like that method is only supported on Firefox.

(started from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array and followed the inheritance chain up.)

bbill
  • 2,264
  • 1
  • 22
  • 28
0

It looks like it's not in Chrome yet but it's working in Chrome Canary which means it's coming to Chrome very soon. Run this in the console to see if slice works already.

new Float32Array().slice

I don't want to convert my typed array to regular array because of performance concerns so I'm looking for a workaround now.

Edit: I just wrote a shim for Float32Array slice which works for me. Soon it will be ignored as soon as Chrome will start supporting slice method.

if (!Float32Array.prototype.slice) {
    Float32Array.prototype.slice = function (begin, end) {
        var target = new Float32Array(end - begin);

        for (var i = 0; i < begin + end; ++i) {
            target[i] = this[begin + i];
        }
        return target;
    };
}
Pawel
  • 16,093
  • 5
  • 70
  • 73