将else部分元素追加到数组的末尾

时间:2017-11-23 05:16:08

标签: javascript jquery html arrays

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("");
}

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

2 个答案:

答案 0 :(得分:0)

通过“追加”你的意思是,结合两个数组?

return result.concat(result2);

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

答案 1 :(得分:0)

没有必要使用两个不同的数组,只需推入相同的数组。

大多数代码在两个分支中是相同的。唯一的区别是添加了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("");
}