1

I am actually new to both spider monkey api and this mailing list. Actually I was trying to create a Array like objectA.arrayA and the call back code goes like this.

    char *value[] = {"abc", "xyz", "efg"};
    int count = 0;
    JSObject* val = JS_NewArrayObject(pContext, 0, NULL);

    while(count < 3) {
        jstr = JS_NewStringCopyZ(pContext, value[count]);

        JS_DefineElement(pContext, val, count++, STRING_TO_JSVAL(jstr),
                        NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
    }

    vJs->DefineProperty(pObject, "arrayA", OBJECT_TO_JSVAL(val));

I am getting the proper value for the objectA.arrayA but when I do objectA.arrayA.length, it says arrayA does not have ay property. Can you tell what i am doing wrong. I am facing the same even when I am creating a sting.

Rituparna Kashyap
  • 1,497
  • 13
  • 19

1 Answers1

1

Your first apparent problem is:

JS_NewArrayObject(pContext, 0, NULL);

Where you have ZERO should be the desired length of your array.

It is pretty apparent to me that you don't know how to use the API. I believe the documentation relavent to your question can be found at:

https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_NewArrayObject

https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_DefineProperty

https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_DefineElement

and: https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JSClass.addProperty

https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_PropertyStub

These five pages have all the info you should need to crack the code.

  • I would not go through the trouble to create an array in hard linked code when you can just pass a const char * to JS_CompileScript to get a Script Object and then call JS_ExecuteScript on that object to create your object from actual JavaScript. The API methods are generally reserved for creating objects that cannot be implemented in javascript alone. –  Mar 31 '12 at 03:15
  • You can learn a lot about hardcoding JavaScript by studying the code that the SpiderMonkey Shell consists of. –  Mar 31 '12 at 03:16
  • It is bad coding practice to use API to do something you could do with javascript. –  Apr 02 '12 at 02:54
  • Actually [JSAPI](https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_NewArrayObject) says is often better to call JS_NewArrayObject(cx, 0, NULL), store the returned object in a GC root, and then populate its elements with JS_SetElement – Rituparna Kashyap Apr 03 '12 at 11:55
  • My bad. In actual program i need to resolved `objectA` twice. Once without defining `arrayA` which is causing all of the problems. It is fine when resolve objectA with arrayA defined. Thanks for the pain though – Rituparna Kashyap Apr 03 '12 at 12:01