JSON stringify将0转换为null

我试图将我的对象转换为JSON,但它不会将我的枚举转换为0.当我打印枚举,我得到0,但是当我在对象内部使用它变为null。 如果我使用string,而不是整数它的作品。

(function () { 'use strict'; var ItemStatus = { 'Prepared': 0, 'Ongoing': 1, 'Finished': 2 }; module.exports = ItemStatus; })(); (function () { 'use strict'; var ItemStatus = require('./itemstatus'); function ItemDetail(detail) { detail = detail || {}; this.message = detail.message || null; this.location = detail.location || null; this.status = detail.status || null; this.date = detail.date || null; } module.exports = ItemDetail; })(); (function () { 'use strict'; var ItemDetail = require('./itemdetail'); var ItemStatus = require('./itemstatus'); function Item(item) { item = item || {} this.name = item.name || null; this.details = item.details || []; this.isFinished = item.isFinished || null; this.finishDate = item.finishDate || null; } Item.prototype.addDetail = function(message, location,date,status) { if (this.isFinished) { this.isFinished = false; } console.log('Status: ' + status); //Prints 0 correctly var detail = new ItemDetail({ message: message, location: location, date:date, status:status }); this.details.push(detail); if (status === ItemStatus.Finished) { this.isFinished = true; this.finishDate = date; } }; module.exports = Item; })(); 

失败的testing

 var should = require('should'); var Item = require('../lib/models/item'); var ItemDetail = require('../lib/models/itemdetail'); var ItemStatus = require('../lib/models/itemstatus'); describe('Item Detail Test:', function() { this.enableTimeouts(false); var myItem = new Item({ name: 'Something', }); myItem.addDetail('Something happened','NY',1212122,ItemStatus.Prepared); myItem.addDetail('Another thing','NY',1412122,ItemStatus.Ongoing); myItem.addDetail('It is done','NY',1212122,ItemStatus.Finished); it('should print JSON', function() { myItem.name.should.eql('Something'); console.log(myItem.details[0].status); myItem.details[0].status.should.eql(ItemStatus.Prepared); console.log(JSON.stringify(myItem)); }); }); 

打印时,我的项目显示如下

 {"name":"Something","details":[{"message":"Something happened","location":"NY","status":null,"date":1212122},{"message":"Another thing","location":"NY","status":1,"date":1412122},{"message":"It is done","location":"NY","status":2,"date":1212122}],"isFinished":true,"finishDate":1212122} 

你的问题与JSON stringify无关。

this.status = detail.status || null; this.status = detail.status || null;0转换为null
因为0是虚的你的this.status将被设置为nulldetail.status0

你可以通过使用1或者不使用this.status = detail.status || null;来启动你的ItemStatus来解决这个问题。 this.status = detail.status || null;

所以要么使用:

 var ItemStatus = { 'Prepared': 1, 'Ongoing': 2, 'Finished': 3 }; 

或者这样做你的testing:

 this.status = detail.status; if( this.status !== 0 && !this.status) { this.status = null; } 

只需致电:

 this.status = detail.status; 

因为,如果detail.status没有定义,它是空的,所以|| null || null是需要的。