【问题标题】:Append the else part elements to end of array将 else 部分元素附加到数组末尾
【发布时间】:2017-11-23 05:16:07
【问题描述】:
function getQuestionHtml(question) {
    var result = [];
    var result2 =[];

    if(question.responses.length > 1) {
        result.push('<div class="question-answered">');
        result.push('<span>' + question.question_text + '</span>');
        console.log(result);
    }
    else{
        result2.push('<div class="question-answered">');
        result2.push('<span>' + question.question_text + '</span>');
        result2.push('<div style="font-size: 12px;">No predictions found for this question.</div>')
        console.log(result2)
    }
    Array.prototype.push.apply(result,result2);
    return result.join("");
}

我想在数组result 的末尾附加result2,但由于if 和else 条件,目前我不想要它的附加替代。 有人可以帮我在result 末尾附加result2。

【问题讨论】:

  • 如果你想在这种情况下追加:question.responses.length &lt; 1,如果不是这样:if(question.responses.length &gt;= 1) {?
  • 这没有意义。如果您正在执行 else 代码,则 result 数组中没有任何内容可附加。
  • 你为什么不直接在两个分支中推入result。

标签: javascript jquery html arrays


【解决方案1】:

“追加”是指将两个数组合并吗?

return result.concat(result2);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

【讨论】:

    【解决方案2】:

    不需要使用两个不同的数组,直接压入同一个数组即可。

    并且大部分代码在两个分支中是相同的。唯一的区别是添加了No predictions found for this question.,所以只在if 中添加。

    function getQuestionHtml(question) {
        var result = [];
        result.push('<div class="question-answered">');
        result.push('<span>' + question.question_text + '</span>');
    
        if(question.responses.length == 0) {
            result.push('<div style="font-size: 12px;">No predictions found for this question.</div>')
        }
        console.log(result)
        return result.join("");
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 2018-04-08
      • 2017-03-03
      • 2012-09-12
      • 2014-11-15
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      相关资源
      最近更新 更多