如何在click事件上为数组添加值

我想要实现的是读取click事件的值并将其保存到数组中。 我的代码:

Add to favourites 
 var hotelName = []; $('.hotel').on('click', function(e){ e.preventDefault(); hotelName.push( $(this).data('hotel-name') ); }); console.log(hotelName.length); 

输出始终为0 。 有人能告诉我,我做错了吗?

你的逻辑很好,你只需要在click处理程序中修改它读取数组的length

 var hotelName = []; $('.hotel').on('click', function(e){ e.preventDefault(); hotelName.push( $(this).data('hotel-name') ); console.log(hotelName.length); // < read the length of the amended array here }); 

工作实例