I am trying to build an array of objects and then either update the object or create a new one depending if one does not exist. This is my first time trying to use the $.grep function and I am not sure what I am doing wrong. Any Advice?
我正在尝试构建一个对象数组,然后更新对象或创建一个新对象,具体取决于是否存在。这是我第一次尝试使用$ .grep函数,我不确定我做错了什么。有什么建议吗?
Here are the objects:
这是对象:
function Phase(phase, html, count) {
this.phase = phase;
this.html = html;
this.count = count;
this.porfolios = [];
}
function Portfolio(portfolio, html, count) {
this.portfolio = portfolio;
this.html = html;
this.count = count;
}
Here is the code in question....
这是有问题的代码....
var phases = [];
//Check Array of Phases
result = $.grep(phases, function (e) { return e.phase == item.Phase; });
if (result.length == 0)
{
var newphase = Phase(item.Phase, itemhtml, 1)
phases.push(newphase);
}
else if (result.length == 1)
{
// update existing phase
result[0].count ++;
result[0].html += itemhtml;
}
2 个解决方案
#1
1
var newphase = Phase(item.Phase, itemhtml, 1)
should be
var newphase = new Phase(item.Phase, itemhtml, 1)
#2
1
You need to use the new
keyword to create an object:
您需要使用new关键字来创建对象:
var newphase = new Phase(item.Phase, itemhtml, 1);
#1
1
var newphase = Phase(item.Phase, itemhtml, 1)
should be
var newphase = new Phase(item.Phase, itemhtml, 1)
#2
1
You need to use the new
keyword to create an object:
您需要使用new关键字来创建对象:
var newphase = new Phase(item.Phase, itemhtml, 1);