这是我的代码的一部分,代码的这一部分显示了html中显示的json数据,但是如果未定义值,则它什么都不显示。我将如何捕获此错误,因此,如果未定义值,它将显示“ N / A”,而不仅仅是中断
var $this=$(this),
movie = $this.data('movie');
$('.active').removeClass('active');
$this.addClass('active');
$("#movieInfo").html(`
<div class="row">
<div class="col-md-4">
<img src="${movie.info.image}" class="thumbnail" style="width:300px;height:400px">
</div>
<div class="col-md-8">
<h4>${movie.title}</h4>
<ul class="list-group">
<li class="list-group-item"><strong>Genre:</strong> ${movie.info.genres}</li>
<li class="list-group-item"><strong>Year:</strong> ${movie.year}</li>
<li class="list-group-item"><strong>Released date:</strong> ${movie.info.release_date}</li>
<li class="list-group-item"><strong>Rank:</strong> ${movie.info.rank}</li>
<li class="list-group-item"><strong>Rating:</strong> ${movie.info.rating}</li>
<li class="list-group-item"><strong>Directors:</strong> ${movie.info.directors}</li>
<li class="list-group-item"><strong>Running Time:</strong> ${movie.info.running_time_secs}</li>
<li class="list-group-item"><strong>Actors:</strong> ${movie.info.actors}</li>
</ul>
</div>
</div>
<div class="row">
<div class="well">
<h5>Plot</h5>
${movie.info.plot}
<hr>
<a href="https://www.rottentomatoes.com/search/?search=${movie.title}" target="_blank" class="btn btn-primary">Rotten Tomatoes</a>
<a href="index.html" class="btn btn-default">Go Back To Search</a>
</div>
</div>
`);
因此,例如,如果未为其中一部电影定义“ movie.info.rating”,我希望它说“ N / A”
最佳答案
如果您对数据进行解构并提供默认值:const {thing = 'N/A'} = movie
如果要内联:{$movie.whatever || 'N/A'}
关于javascript - 值未定义时如何捕获Json数据错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59601514/