为什么此代码日志返回false?

时间:2016-07-04 19:03:07

标签: javascript if-statement for-loop

我无法弄清楚为什么这个代码段会记录错误。我确信它应该记录下来。我做错了什么?



var hasElb = function(string12b,char12b) {
    var el = [];
    for (var i = 0; i < string12b.length; i++ ) {
        if (string12b[i] === char12b) {
            el += char12b;
        }
    }
    if (el[0] === char12b) {
        console.log(true + " el[0] = " + el[0] + " and char12b = " + char12b);
    }
    else {
        console.log(false + " el[0] = " + el[0] + " and char12b = " + char12b);
    }
};
hasElb([1,3,5,7,9,11],7);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

要向数组添加元素,请使用.push(),而不是+=

    if (string12b[i] === char12b) {
        el.push(char12b);
    }