![](/img/trans.png)
[英]How do I loop through an array (recurision) and push object key/value pairs in another array?
[英]How to push an object with two key/value pairs into an array?
我想將此數組作為參數
var movies = ['matrix','the dark knight','a beautiful mind','american pie']
用於循環遍歷該數組並將標題作為對象推入新數組的函數,並在此過程中添加一個ID(來自循環索引)。
新的arr應該看起來像這樣
['{title:matrix, id:0}','{title:the dark knight, id:1}','{title:a beautiful mind, id:2}','{title:american pie, id:3}']
這是函數,我知道我有語法錯誤。 但是哪里?
function addToList(arr) {
var movieList = []
for (var x of arr) {
movieList{["titel"]=arr, ["id"]=x}
}
return movieList
}
您可以簡單地使用.map()
獲得所需的輸出:
const data = ['matrix','the dark knight','a beautiful mind','american pie'] const result = data.map((m, i) => ({title: m, id: i})); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
不使用array.map
function addToList(arr) {
var movieList = []
for (var i in arr) {
movieList[i]={title:arr[i], id:i}
}
return movieList
}
要么
function addToList(arr) {
var movieList = []
for (var i in arr) {
movieList.push({title:arr[i], id:i});
}
return movieList
}
function addToList(arr) { var movieList = [] for (var x of arr) { movieList.push({titel: arr, id: x}); } return movieList }
for ... of語句遍歷對象的值,而不遍歷索引(屬性)。
您可以使用for ... in語句遍歷對象的索引(屬性)。
var movies = ['matrix','the dark knight','a beautiful mind','american pie']; function addToList(arr) { var movieList = []; for (var i in arr) { movieList[i] = {"title": arr[i], "id": i}; } return movieList; } console.log(addToList(movies));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.