这是我想要实现的目标。
我有以下JSON响应。我正在使用$ .getJSON方法加载JSON数据并通过检查它是否是如下数组而将其添加到集合中。
{
"r": [{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
}]
}
我将loadFromJson1和loadFromJson2函数的json响应作为参数传递,如下所示。
var tablesResult = loadFromJson1(resultstest.r[0].Clg);
loadFromJson1 = function (input) {
if (_.isArray(input)) {
alert("loadFromJson1: Inside array function");
var collection = new CompeCollection();
_.each(input, function (modelData) {
collection.add(loadFromJson1(modelData));
});
return collection;
}
return new CompeModel({
compeRates: loadFromJson2(input),
compName: input.Name
});
};
loadFromJson2 = function (input)
// here is the problem, the 'input' is not an array object so it is not going to IF condition of the isArray method. Hence i am trying to convert into array object.
{
if (_.isArray(input)) {
alert("loadFromJson2: Inside array function");
//alert is not coming here though it is array
var rcollect = new rateCollection();
_.each(input, function (modelData) {
rcollect.add(modelData);
});
return rcollect;
}
};
上面的代码我将loadFromJson1和loadFromJson2函数的json responeses作为“input”传递。 isArray仅在loadFromJson1函数上变为true,并在if条件内发出警告但在loadFromJson2函数中没有,但我传递相同的参数。
你能告诉我我在这里犯的错误吗?答案 0 :(得分:0)
您的代码有点分散,函数loadFromJson1重复。还有一些对象没有发布在问题中。
然而,我确实创造了fiddle的工作;打印“内部数组功能”......loadFromJson1的简化版本,它正在小提琴中工作:
loadFromJson1 = function (input) {
var resArray = $.map(input, function (value, index) {
return [value];
});
if (_.isArray(resArray)) {
console.log("Inside array function");
}
};