2017-07-23 208 views
-1
var comments = {}; 
comments.data = ["Good!", "Bye", "I hate it..."]; 
comments.print = function() { 
    this.data.forEach(function(el) { 
    console.log(comments.print()); 
    }); 
} 

它应该打印评论内的数据(“好!”,“再见”,“我讨厌它......”)。评论是一个对象。我可以在花括号里面定义这个函数,但是我想用不同的语法来完成它。这是什么错这个JS程序

+6

无限循环?将'console.log(comments.print());'改为'console.log(el); ' –

+0

它会进入循环。访问功能,然后再完全定义它 –

回答

1

它在递归中运行。它自称。所以它的无限。与EL

更换comments.print()试试这个:

var comments = {}; 
comments.data = ["Good!", "Bye", "I hate it..."]; 
comments.print = function() { 
    comments.data.forEach(function(el) { 
    console.log(el); 
    }); 
} 
comments.print(); 
+0

在这两种情况下它在控制台中返回相同的值http://i.imgur.com/M6s2DYv.png – vksz

+1

现在尝试它,我错过了一些东西 –

0

你调用print()到您的print()函数,所以这可能会导致一个无限循环。我想在每个循环你想记录“好”,然后“再见”,然后“我讨厌它”,所以你只需要拨打el而不是评论至少是整个对象?

var comments = {}; 
 
comments.data = ["Good!", "Bye", "I hate it..."]; 
 
comments.print = function() { 
 
    this.data.forEach(function(el) { 
 
     console.log(el); 
 
    }); 
 
} 
 

 
comments.print() ;