简体   繁体   中英

Complex objects in javascript

I'm fiddling around with a library called bcoin for node. Running the following code:

  chain.on('block', function(block) {
    console.log('Connected block to blockchain:');
    block.txs.forEach(function(t) {
      t.inputs.forEach(function(i) {
        console.log(typeof i, i);
        console.log(JSON.stringify(i));
      });
    });
  });

This is the response I'm getting:

Connected block to blockchain:
object { type: 'coinbase',
  subtype: null,
  address: null,
  script: <Script: 486604799 676>,
  witness: <Witness: >,
  redeem: null,
  sequence: 4294967295,
  prevout: <Outpoint: 0000000000000000000000000000000000000000000000000000000000000000/4294967295>,
  coin: null }
{"prevout":{"hash":"0000000000000000000000000000000000000000000000000000000000000000","index":4294967295},"script":"04ffff001d02a402","witness":"00","sequence":4294967295,"address":null}

Notice that even though the attribute type for example, is shown when we print i , that attribute does not exist when we JSON.stringify the object. If I tried to console.log(i.type) I'd get undefined .

How is that possible? And what is a good way of debugging what's going on with an object?

JSON.stringify will only includes enumerable properties that are not functions.

So if you define a property and set as non-enumerable, it will not be a part of JSON string.

 var obj = { a: 'test' }; // Non-enumerable property Object.defineProperty(obj, 'type', { enumerable: false, value: 'Test' }); // Get property Object.defineProperty(obj, 'type2', { get: function(){ return 'Test 2' } }); console.log(JSON.stringify(obj), obj); console.log(obj.type, obj.type2) 

在此处输入图片说明

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