簡體   English   中英

如何從 Javascript 中的數組中分配 object 值

[英]How to assign object values from an array in Javascript

我為名為“Book”的 object 創建了一個構造函數。 我已經從數組中的表單中捕獲了所有值。 現在我想將此數組的值分配給此構造函數。 但是,我很困惑,因為我似乎沒有在 Google 或 StackOverflow 上找到我想要的東西。

這是我的代碼:

let formArray = [];
document.querySelectorAll('input[type="text"]').forEach(function (node) {
    formArray.push(node.value);
});

let newBook = new Book();
let idx = 0;
Object.keys(newBook).forEach(function (k) {
    k = formArray[idx];
})

但是,這是我的日志:

Book {title: undefined, author: undefined, nPages: undefined, isRead: undefined}
title: undefined
author: undefined
nPages: undefined
isRead: undefined

請幫我解決這個問題!

這就是你如何設置你所追求的東西,為了簡單起見,我只包括了兩個屬性。

 class Book { constructor({ title, author }) { this.title = title this.author = author } } const values = {} document.querySelectorAll('input[type="text"]').forEach(function (node) { values[node.name] = node.value }); console.log(new Book(values))
 <input type="text" name="title" value="The Never Ending Story" /> <input type="text" name="author" value="Michael Ende" />

 let formArray = []; document.querySelectorAll('input[type="text"]').forEach(function (node) { formArray.push(node&&node.value); }); let newBook = new Book(); let idx = 0; Object.keys(newBook).forEach(function (k) { k = formArray[idx]; })

試試這個我認為js在node.value之前運行代碼

暫無
暫無

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

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