我有一個普遍的問題,我想知道如果任何人有解決它,然後一個更好的方式是我迄今已做的事情。做的東西,如果for循環沒有找到我想要的
我想遍歷數組找到一個對象,並對其進行更新。如果該對象不存在,我想將它追加到數組中。我通常使用更復雜的對象,這使問題更加複雜。
var movies = [
{ _id: 1, title:"Movie 1" },
{ _id: 2, title: "Another Movie" }
];
var myTheater = { location:"here", current_movies: movies };
// A movie to check. The _id may or may not be in movies.
var aMovie = { _id: 3, title: "Something New" };
// boolean flag to let us know if something happened
var updated = false;
// look through all movies and my theater and update as needed
for(var i = 0, len = myTheater.current_movies.length; i<len; i++){
if(myTheater.current_movies[i]._id === aMovie._id){
console.log("Updating movie name.");
myTheater.current_movies[i].title = aMovie.title;
updated = true;
break;
}
}
// check if anything was updated and add the movie if not
if(!updated){
myTheater.current_movies.push(aMovie);
}
有沒有更好的方法來做到這一點,或使用標誌的最佳選擇?謝謝!
你應該使用'break'結束循環您找到對象之後,除非可以有多個匹配。 – Barmar