wet*_*ems 4 javascript arrays function object arrayobject
我了解将对象添加到数组所需的命令。我知道它的array.push(object)
.
但是,假设我有这个对象数组:
const artists = [{
"rank": 1,
"name": "Rakim",
"year": 1985,
"album": "Paid in Full",
},
{
"rank": 2,
"name": "Nas",
"year": 1994,
"album": "Illmatic"
}
]
Run Code Online (Sandbox Code Playgroud)
如果我需要添加一个具有功能的新功能。我该怎么做?我想让它成为一个功能,允许我在未来添加多个。
所以像,
function addArtist(array {}) {
return array;
}
console.log(addArtist(array {
new object here
}));
Run Code Online (Sandbox Code Playgroud)
您需要使用 将一个array
对象传递给函数,并将其传递给初始对象artists
(应该是let
)spread operator
:
let artists = [
{
"rank": 1,
"name": "Rakim",
"year": 1985,
"album": "Paid in Full"
},
{
"rank": 2,
"name": "Nas",
"year": 1994,
"album": "Illmatic"
}
]
function addArtist (artistsToAdd) {
artists.push(...artistsToAdd);
return artists;
}
const objects = [
{
"rank": 3,
"name": "Bob",
"year": 1995,
"album": "Album3"
},
{
"rank": 4,
"name": "Nas",
"year": 1992,
"album": "Album4"
}
];
console.log(addArtist(objects));
Run Code Online (Sandbox Code Playgroud)
您还可以使用concat
将对象添加到列表中。
归档时间: |
|
查看次数: |
70 次 |
最近记录: |