如何在Javascript中从数组分配对象值
我为一个名为“Book”的对象创建了一个构造函数。我已经从数组中的一个窗体中捕获了所有值。现在我想把这个数组的值赋给这个构造函数。然而,我被卡住了,因为我似乎在Google或StackOverflow上找不到我想要的东西 这是我的密码:如何在Javascript中从数组分配对象值,javascript,ecmascript-6,Javascript,Ecmascript 6,我为一个名为“Book”的对象创建了一个构造函数。我已经从数组中的一个窗体中捕获了所有值。现在我想把这个数组的值赋给这个构造函数。然而,我被卡住了,因为我似乎在Google或StackOverflow上找不到我想要的东西 这是我的密码: let formArray = []; document.querySelectorAll('input[type="text"]').forEach(function (node) { formArray.push(node.value); });
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
请帮我弄清楚
让formArray=[];
document.querySelectorAll('input[type=“text”]”)。forEach(函数(节点){
formArray.push(节点和节点值);
});
let newBook=新书();
设idx=0;
Object.keys(newBook.forEach)(函数(k){
k=形式阵列[idx];
})
这就是您如何设置所需内容的方法,为了简单起见,我只提供了两个属性
教材{
构造函数({title,author}){
this.title=标题
this.author=作者
}
}
常量值={}
document.querySelectorAll('input[type=“text”]”)。forEach(函数(节点){
值[node.name]=node.value
});
console.log(新书(值))
您确定您正在获取node.value吗?是的formArray.push(node.value)
按预期工作,控制台.log(formArray)
返回:[“1”、“1”、“1”、“1”]
(例如)。是的,因为它工作很晚,我在下面对此进行了解释