开发者

ActionScript: An equivalent of Python's `repr` (ie, a useful string representation of an object)?

开发者 https://www.devze.com 2022-12-20 06:47 出处:网络
Python\'s repr function is awesome: it returns a printable representation of an object. For example, repr([\"a\'b\", {1: 2}, u\"foo\"]) is the string \'[\"a\\\'b\", {1: 2}, u\\\'foo\\\']\'. Notice,

Python's repr function is awesome: it returns a printable representation of an object.

For example, repr(["a'b", {1: 2}, u"foo"]) is the string '["a\'b", {1: 2}, u\'foo\']'. Notice, eg, how quotes are properly escaped.

So, is there anything like this for ActionScript?

For example, right now: [1, 2, ["3", "4"]].toString() produces the string "1,2,3,4"… Which really isn't very helpful. I'd like it to produce a string like… Well, '[1, 2, ["3", "4"]]'.

I have considered using a JSON library… But that's less than ideal, b开发者_开发问答ecause it will try to serialize instances of arbitrary objects, which I don't really want.


AFAIK there isn't any quick-easy one line command that does what you want, but here's a way to do it, straight from Adobe I might add

http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html


This is the only thing remotley close:

valueOf ()

public function valueOf():Object

Language Version : ActionScript 3.0 Runtime Versions : AIR 1.0, Flash Player 9

Returns the primitive value of the specified object. If this object does not have a primitive value, the object itself is returned.

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, A subclass of Object implements function valueOf():Object instead of using an override of the base class.

Returns Object — The primitive value of this object or the object itself.


You can try the ObjectUtil.toString function, it's not exatly what you want, but I don't think you will find anything closer to what you want as it's functions is described as "Pretty-prints the specified Object into a String.", which is what it does, but keeps much more info that you would want. As Array is a complex data object and that's why it annotates it like that.

    var a:Array = [1, 2, ["3", "4"]];
    trace (ObjectUtil.toString(a));
    // returns
    // (Array)#0
    //  [0] 1
    //  [1] 2
    //  [2] (Array)#1
    //    [0] "3"
    //    [1] "4"

I'm wondering how would repr handle this example:

    var a:Array = [0,1,2];
a.push(a);                  
trace (ObjectUtil.toString(a));
    // returns
    // (Array)#0
    //   [0] 0
    //   [1] 1
    //   [2] 2
    //   [3] (Array)#0


Yes I know what you want, the solution is quite simple, use JSON object to complete it!

For example:

trace(JSON.stringify('hello'));
trace(JSON.stringify(['yet', 'another']));
trace(JSON.stringify({hello: 'world'}));

Try it!

Read more about that please visit here.

0

精彩评论

暂无评论...
验证码 换一张
取 消