我有一个像这样的for循环:
for(var i = 0; i < data.reviews.length; i++){
if(data.reviews[i].rating.overall > 80){
console.log(i);
if(i > 1){
console.log('more than 80 and more than 1');
}
else{
console.log('more than 80 and only 1');
}
}
}
和评论数组如下:
"reviews":[
{
"rating":{"overall": 91}
},
{
"rating":{"overall": 77}
},
{
"rating":{"overall": 94}
},
{
"rating":{"overall": 74}
}
],
我有一些条件需要我来附加一些HTML:
1)如果整体评论超过80且有多个评论(附加幻灯片放映)
2)如果整体评论超过80而且只有一篇评论(附加纯文本,没有幻灯片的jus音评)
根据提供的评论数据,我应该只在我的控制台中打印两次console.log('more than 80 and more than 1');
:
more than 80 and only 1
more than 80 and only 1
more than 80 and more than 1
答案 0 :(得分:1)
如果我正确理解你的问题,那么你只需要更改内部if
语句来检查有多少评论 - 而不是迭代它们的计数器......
var data = {
"reviews": [
{
"rating":{"overall": 91}
},
{
"rating":{"overall": 77}
},
{
"rating":{"overall": 94}
},
{
"rating":{"overall": 74}
}
]
};
for (var i = 0, l = data.reviews.length; i < l; i++) {
if (data.reviews[i].rating.overall > 80) {
if (l > 1) { // check the overall count, instead of the current index
document.write('more than 80 and more than 1<br />');
}
else {
document.write('more than 80 and only 1<br />');
}
}
}
答案 1 :(得分:0)
试试这个〜
var count = 0;
for(var i = 0; i < data.reviews.length; i++){
if(data.reviews[i].rating.overall > 80){
count++;
}
}
if(count > 1){
console.log('more than 80 and more than 1');
}
else{
console.log('more than 80 and only 1');
}
//current.find(".reviews-wrapper ul").append("<li data-orbit-slide='headline-" + [i] + "'>" + data.reviews[i].notes + "<p class='bold'>" + data.reviews[i].user.nickname + ", " + data.reviews[i].groupInformation.groupTypeCode + ", " + data.reviews[i].groupInformation.age + "</p></li>");
答案 2 :(得分:0)
你是否想要将评分超过80?
var count = 0
for(var i = 0; i < data.reviews.length; i++){
var rating = data.reviews[i].rating.overall;
switch (rating) {
case (rating > 80):
count++;
break;
}
}
if ( count > 1 ) {
console.log('more than 80 and more than 1');
} else {
console.log('more than 80 and only 1');
}
如果您想进一步使用开关/案例,您可以使用每个括号附加所需的html
答案 3 :(得分:0)
因此,您提供的代码所遇到的问题是它与您的问题不符。 您要求三种情况:
但是,您正在使用&#39; i&#39;你的迭代器回答的问题是“是否有多个评论”,在这种情况下它会回答问题&#39;当前迭代是否是此循环的第三次或以后的迭代而不是评论&#39 ; (由于数组的零索引,&#39; i&gt; 1&#39;在第三次迭代时将为真。)
从您的问题中不清楚您是否只想将超过80的评论计入您的总数或仅仅是评论总数,因此我会给您一些循环选项:
var sizeString=''
if(data.reviews.length > 1) {
sizeString=' and more than 1';
}
for(var i = 0; i< data.reviews.length; i++) {
if(data.reviews[i].rating.overall > 80){
console.log('more than 80'+sizeString);
}
}
或者,如果只计算超过1次超过80次审核:
var sizeString=''
var numOver80=0;
for(var i = 0; i< data.reviews.length; i++) {
// This will simply find out if there are at least two over 80 ratings
if(data.reviews[i].rating.overall > 80){
numOver80++;
if(numOver80 > 1){
sizeString=' and more than 1';
break; // Unless you want to get the actual total
}
}
}
for(var i = 0; i< data.reviews.length; i++) {
if(data.reviews[i].rating.overall > 80) {
console.log('more than 80'+sizeString);
}
}
希望这些能让你指向正确的方向。