簡體   English   中英

向現有的javascript對象添加新屬性

[英]Adding new property to existing javascript object

我正在嘗試將格式:“電影”添加到數組中的每個對象,但是我無法弄清楚。

var movie = [
    {title: "A Clockwork Orange", year: "1971", raiting: "8.3", genre: "Crime, Drama, Sci-Fi"},
    {title: "Full Metal Jacket", year: "1987", raiting: "8.3", genre: " Drama, War"},
    {title: "Pulp Fiction", year: "1994", raiting: "8.9", genre: "Crime, Drama"},
    {title: "Fight Club", year: "1999", raiting: "8.8", genre: "Drama"},
    {title: "Interstellar", year: "2014", raiting: "8.6", genre: "Adventure, Drama, Sci-Fi"}
];


movie.forEach(function () {
    movie.format = "film";
});


movie.forEach(function (element) {
    console.log(element);
});

您需要向function傳遞參數,並向其中添加新屬性

movie.forEach(function (element) {
    element.format = "film";
});

使用goes to運算符。

 var movie = [ {title: "A Clockwork Orange", year: "1971", raiting: "8.3", genre: "Crime, Drama, Sci-Fi"}, {title: "Full Metal Jacket", year: "1987", raiting: "8.3", genre: " Drama, War"}, {title: "Pulp Fiction", year: "1994", raiting: "8.9", genre: "Crime, Drama"}, {title: "Fight Club", year: "1999", raiting: "8.8", genre: "Drama"}, {title: "Interstellar", year: "2014", raiting: "8.6", genre: "Adventure, Drama, Sci-Fi"}]; let i = movie.length; while (i --> 0) movie[i].format = 'film'; console.log(movie); 
 .as-console-wrapper { max-height: 100% !important } 

如果您也喜歡ES6,則可以使用粗箭頭進行確認。

movie.forEach(element => element.format = "film");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM