不理解这个forEach()方法的输出

时间:2013-09-01 22:42:13

标签: javascript

考虑这个例子:

var a = {
    "Check" : function doThis(value, index, ar) { 
        if(value >= 10) {
            document.write(value + ", ");
        }
        else {
            document.write("The array element is less than 10, ");
        }
    }       
}

var arr = [12, 20, 2, 3, 15];
document.write(arr.forEach(a.Check)); 

结果是:

12, 20, The array element is less than 10, 
The array element is less than 10, 15, undefined

我不明白为什么数组中有一个未定义的额外元素。它是否与在对象中定义回调函数有关?

1 个答案:

答案 0 :(得分:2)

取代:

document.write(arr.forEach(a.Check)); 

使用:

arr.forEach(a.Check); 

使用document.write(arr.forEach(a.Check));打印arr.forEach()调用返回的内容(undefined