1

我有一个调用 api 的 javascript 应用程序,并且 api 返回 json。使用 json,我选择了一个特定的对象,然后循环遍历它。

我的代码流程是这样的:服务调用-> GetResults 循环通过结果和构建页面

但问题是,有时 api 只返回一个结果,这意味着它返回一个对象而不是数组,所以我不能循环遍历结果。解决这个问题的最佳方法是什么?

我应该将我的对象或单个结果转换为数组吗?将其放入/推送到数组中?或者我应该做一个 typeof 并检查元素是否是一个数组,然后进行循环?

谢谢您的帮助。

//this is what is return when there are more than one results
var results = {
pages:  [
        {"pageNumber":204},
        {"pageNumber":1024},
        {"pageNumber":3012}
    ]
}

//this is what is returned when there is only one result
var results = {
    pages: {"pageNumber": 105}
}

我的代码循环遍历结果,只使用一个 for 循环,但它会产生错误,因为有时结果不是数组。再说一遍,我是否检查它是否是一个数组?将结果推送到新数组中?什么会更好。谢谢

4

2 回答 2

6

如果您无法控制服务器端,您可以做一个简单的检查以确保它是一个数组:

if (!(results.pages instanceof Array)) {
    results.pages = [results.pages];
}

// Do your loop here.

否则,理想情况下这应该发生在服务器上;始终可以以类似方式访问结果应该是合同的一部分。

于 2012-12-26T23:38:39.707 回答
0

将您对循环内的对象所做的任何事情安排到一个单独的过程中,如果您发现该对象不是数组,请直接将该过程应用于它,否则,将其多次应用于该对象的每个元素:

function processPage(page) { /* do something to your page */ }

if (pages instanceof Array) pages.forEach(processPage);
else processPage(pages);

Obvious benefits of this approach as compared to the one, where you create a redundant array is that, well, you don't create a redundant array and you don't modify the data that you received. While at this stage it may not be important that the data is intact, in general it might cause you more troubles, when running integration and regression tests.

于 2012-12-27T14:03:35.847 回答