繁体   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