谷歌控制台中的Javascript

Javascript in the Google Console

本文关键字:Javascript 控制台 谷歌      更新时间:2023-09-26
 // Create movie DB
var movies = [
    {
        title: "Avengers",
        hasWatched: true,
        rating: 5
     },
    {  
        title: "SpiderMan",
        hasWatched: false,
        rating: 4
      },
    {
        title: "LightsOut",
        hasWatched: true,
        rating: 6
     }
]
// Print it out
movies
// Print out all of them 
movies.forEach(function(movie)){
  var result = "You have ";
  if(movie.hasWatched){
       result += "watched ";
}else{
       result += "not seen ";
}
  result += "'" + movie.title + "'"-";
  result += movie.rating + " stars";
  console.log(result);
}

为什么我的第一个对象是真的,但控制台打印出"你没有看到《复仇者联盟》-5颗星">

您在这一行出现语法错误:

result += "'" + movie.title + "'"-";

应使用进行修复

result += '"' + movie.title + '"- ';

在JavaScript中,双引号和单引号都可以使用,如果你想打印出双引号("(,你可以用单引号(例如:'"'("包装"它们。

关于何时使用双引号/单引号的有趣讨论可以在这里找到。

var movies = [{
  title: "Avengers",
  hasWatched: true,
  rating: 5
}, {
  title: "SpiderMan",
  hasWatched: false,
  rating: 4
}, {
  title: "LightsOut",
  hasWatched: true,
  rating: 6
}]
// Print it out
console.log(movies);
// Print out all of them 
movies.forEach(function(movie) {
  var result = "You have ";
  if (movie.hasWatched) {
    result += "watched ";
  } else {
    result += "not seen ";
  }
  result += '"' + movie.title + '"- ';
  result += movie.rating + " stars";
  console.log(result);
});

这是更新后的代码。修复了一些语法错误!

var movies = [{
  title: "Avengers",
  hasWatched: true,
  rating: 5
}, {
  title: "SpiderMan",
  hasWatched: false,
  rating: 4
}, {
  title: "LightsOut",
  hasWatched: true,
  rating: 6
}]
// Print it out
console.log(movies);
// Print out all of them
movies.forEach(function(movie) {
  var result = "You have ";
  if (movie.hasWatched) {
    result += "watched ";
  } else {
    result += "not seen ";
  }
  result += '"' + movie.title + '" - ';
  result += movie.rating + " stars";
  console.log(result);
});