简体   繁体   中英

Why am i getting output as [object Object] instead of [Id: id_value] when using Spidermonkey

I was using vi editor on my mac terminal and writing some Javascript codes. When i used Spidermonkey Engine to run on this code:

 function getPerson(id) { if (id < 0) { throw new Error('ID must not be negative: '+id); } return { id: id }; } function getPersons(ids) { var result = []; ids.forEach(function (id) { try { var person = getPerson(id); result.push(person); } catch (exception) { print(exception); } }); return result; } 

When i run the following commands:

js -f exc.js -i
js> getPersons([1,-2,3]);

I get the following response:

Error: ID must not be negative: -2
[object Object],[object Object]

Instead of:

Error: ID must not be negative: -2
{ id: 1 }, { id: 3 }

So, how am i supposed to correct this?

If you have control on where the object is printed, try using JSON.stringify on the object before printing it.

Possibly this may work (not tested):

js> JSON.stringify(getPersons([1,-2,3]));

JSON, as in the other answer, is often a useful and fast way to peruse the contents of simple objects. But if you want to customise the output per object (eg when using complex objects, factories, classes...), or if you want to use console.log directly, you should implement the toString() method:

var person = {
  id: 123,
  toString: function() {
    return '[Id: ' + this.id + ']'
  }
};

person
//=> [Id: 123]

Note that the behaviour of JS shells varies. For example, while your JS shell seems to call toString() to print values (the default toString() implementation returns [object Object] ), Node.js will have "more helpful" behaviour akin to pretty-printing objects and variables and functions in a native-looking way:

> console.log(person)
{ id: 123 }

Even my local version of SpiderMonkey has different behaviour than yours:

js> person
({id:123})

So don't rely on this output for anything robust. If you want something that calls toString() implicitly and reliably in SpiderMonkey, use either good old string coercion:

js> ''+person
"[Id: 123]"

Or the print() function:

js> print(person)
[Id: 123]

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