Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working on a game and we make extensive use of typed arrays (Float32Arrays) for our math types. We save and load the gamestate from JSON. An example of JSON stringify output is for such an array (in Chrome) is:

"{"0":0,"1":0,"2":0,"length":3,"byteLength":12,"byteOffset":0,"buffer":{"byteLength":12}}"

This wastes space and causes them to be loaded as objects which is inconvenient. Ideally we could use the stringify 'replacer' function to test if a variable is a typed array, and then convert it to a bog standard array in that case. Unfortunately I'm not sure how to reliably test whether a variable is a typed array or not.

Any help?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

You can use the Object.prototype.toString.call(yourObject) trick. That returns a useful string for all of the JavaScript built-in types ([object Array], [object Date], etc.).

On Chrome, Firefox, and Opera, at least, it returns [object Float32Array] for a Float32Array, so:

if (Object.prototype.toString.call(yourObject) === "[object Float32Array]") {
     // It's a Float32Array
}

Try your browser here | Source

share|improve this answer
    
Thanks! This works great. –  AGD Mar 6 '13 at 16:58
    
@user2140622: You're welcome! –  T.J. Crowder Mar 6 '13 at 17:05
    
@user2140622: If this answered your question, the way Stack Overflow works, you click the checkmark next to the answer to "accept" it. More: meta.stackexchange.com/questions/5234/… (But only if it answered the question.) –  T.J. Crowder Mar 6 '13 at 17:06

You also can use yourObject instanceof Float32Array construction. It returns true if your object is an instance of Float32Array and false in other case.

if (yourObject instanceof Float32Array) {
    // your code here
}
share|improve this answer

If you'd like a more general test that catches any of the ArrayBufferView and DataView types you can use:

if (Object.prototype.toString.call(yourObject.buffer) === "[object ArrayBuffer]") {
     // It's either an ArrayBufferView or a DataView
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.