简体   繁体   中英

Why isn't .slice() working with Float32Array() but does with an Array()? [JavaScript]

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();

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();

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;
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM