将新属性添加到现有javascript对象

时间:2018-02-13 21:07:49

标签: javascript arrays object foreach properties

我正在尝试添加格式:“电影”到数组中的每个对象,但我无法弄明白。

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

3 个答案:

答案 0 :(得分:3)

您需要将参数传递给function并将新属性添加到其中

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

答案 1 :(得分:1)

使用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
}

答案 2 :(得分:0)

如果你也参加了ES6,你肯定可以用胖箭来做这件事。

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