问题描述:

I'm thinking about typed arrays in javascript; in particular, reading binary file headers. Reading the MDN Typed Arrays documentation, they blithely say we can represent the C struct:

struct someStruct {

unsigned long id;

char username[16];

float amountDue;

};

with the javascript:

var buffer = new ArrayBuffer(24);

// ... read the data into the buffer ...

var idView = new Uint32Array(buffer, 0, 1);

var usernameView = new Uint8Array(buffer, 4, 16);

var amountDueView = new Float32Array(buffer, 20, 1);

and then you can say amountDueView[0] but seem oblivious to the fact that treating a scalar as a one-element array is terrible and being able to say something like sizeof(someStruct) is useful as well.

So... is there something better? MDN makes reference to js-ctypes but it's no standard javascript.

Edit: Yes, I know about javascript objects. Modeling the data isn't the problem; reading and writing binary data elegantly is.

网友答案:

Can't you just define an object in JS to model this?

var someObject =  {
  Id:2,
  username: [],
  amountDue:5
};
网友答案:

For what it's worth, there's jBinary, which lets you do stuff like:

var binary_data = '\x0f\x00\x00\x00Bruce\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xecQXA';

var myTypeset = {
    'jBinary.all': 'someStruct',
    'jBinary.littleEndian': true,
    someStruct: {
        id: 'uint32',
        username: ['string0', 16],
        amountDue: 'float'
    }
};

var binary = new jBinary(binary_data, myTypeset);
header = binary.readAll(); // Object {id: 15, username: "Bruce", amountDue: 13.520000457763672}

header.username = "Jim";
binary.writeAll(header);
binary.readAll(); // Object {id: 15, username: "Jim", amountDue: 13.520000457763672}

It's not particularly well-documented (an example like the above would be very welcome) but it's quite good.

The biggest caveat is that it relies on javascript objects having properties remain in the order they're defined, which is practically the case but not part of the javascript spec. I suspect this will never actually change because it would break a kajillion things, but still.

网友答案:

You more than likely don't need typed arrays for your application; the rest of the world has been surviving just fine without them. IE < 10 doesn't even support them.

You can write the object like this

var data = {id: 123, username: "bob", amountDue: 123.45};

And read from it like this

data.id;
// 123

data.username;
// "bob"

Try to read an unset key

data.foo;
// undefined

And set a key after it's defined

data.foo = "bar";
// "bar"

And delete the key

delete data.foo;
// true

Try to read a deleted key

data.foo;
// undefined
相关阅读:
Top