简体   繁体   English

向现有的javascript对象添加新属性

[英]Adding new property to existing javascript object

I am trying to add format: "film" to each object in the array but I can't figure it out. 我正在尝试将格式:“电影”添加到数组中的每个对象,但是我无法弄清楚。

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

You need to pass an argument to function and add the new property to it 您需要向function传递参数,并向其中添加新属性

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

Using goes to operator. 使用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