我正在使用一个节点模块来返回一些数据。数据将通过以下两种方式之一返回:
单一记录
single = {"records[]":{"name":"record1", "notes":"abc"}}
多条记录
multiple = {"records[]":[{"name":"record1", "notes":"abc"},{"name":"record2", "notes":"xyz"}]}
如果我调用以下命令,我可以从单个记录中获取值
single['records[]'].name // returns "record1"
如果有多张唱片我会这样打电话给你
multiple['records[]'][0].name // returns "record1"
当我返回一条记录,但将其视为多条记录时,就会出现问题
single['records[]'][0].name // returns undefined
现在我这样测试:
var data = nodemodule.getRecords();
if(data['records[]'){ //test if records are returned
if(data['records[]'].length){ //test if 'records[]' has length
// ... records has a length therefore multiple exist
// ... for loop to loop through records[] and send data to function call
} else {
// .length was undefined therefore single records
// single function call where I pass in records[] data
}
}
这是测试单记录还是多记录的最佳方法,因为我受到了节点模块返回的内容的限制,还是我遗漏了一些更简单的方法?