2016-08-04 41 views
0
// 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星」JavaScript中的谷歌控制檯

+0

謝謝你們了我的錯! – Simon

回答

0

你在這一行有一個語法錯誤:

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

應固定:

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

在的javascrip如果您想打印出雙引號("),可以使用單引號ex:'"'「包裝」它們。

有關何時使用雙/單引號的討論可以參見here

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); 
 
});

0

這裏是更新的代碼。修復了一些語法錯誤!

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); 
 
});