我試圖將“allValues”陣列中的值放在記憶體物件中現有的鍵中,但它們只是在現有鍵之后被添加到物件中,它們的鍵是索引號。如何在現有鍵中插入值?
const memories = {
email: '',
date: '',
relation: '',
tips: '',
location: '',
};
const backend = (e) => {
e.preventDefault();
const allInputs = Array.from(document.querySelectorAll('input'));
const allValues = allInputs.map(input => input.value);
for (const [index, value] of allValues.entries(){
memories[index] = value;
}
console.log(memories);
};
uj5u.com熱心網友回復:
您將輸入值作為陣列檢索,因此您沒有任何有關表單欄位名稱的資訊。
你可能想要這樣的東西:
const allInputs = Array.from(document.querySelectorAll('input'));
const allValues = allInputs.map(({name, value}) => ({name, value}));
for (const {name, value} of allValues) {
memories[name] = value;
}
完整片段:
const memories = {
email: '',
date: '',
relation: '',
tips: '',
location: '',
};
const allInputs = Array.from(document.querySelectorAll('input'));
const allValues = allInputs.map(({name, value}) => ({name, value}));
for (const {name, value} of allValues) {
memories[name] = value;
}
console.log(memories);
<input name="email" value="[email protected]">
<input name="location" value="World">
uj5u.com熱心網友回復:
請參閱CodeSandbox的作業示例。
索引.html
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta charset="UTF-8" />
</head>
<body>
<input type="text" name="email" value="a" />
<input type="text" name="date" value="b" />
<input type="text" name="relation" value="c" />
<input type="text" name="tips" value="d" />
<input type="text" name="location" value="e" />
<button onclick="backend()">Submit</button>
<script src="src/index.js"></script>
</body>
</html>
index.js
const memories = {
email: "",
date: "",
relation: "",
tips: "",
location: ""
};
window.backend = () => {
const allInputs = Array.from(document.querySelectorAll("input"));
allInputs.forEach((input) => {
memories[input.name] = input.value;
});
console.log(memories);
};
uj5u.com熱心網友回復:
name為每個輸入設定 a屬性。該document.querySelectorAll()方法回傳 a NodeList,您可以使用 對其進行迭代for..of。解構回圈中的nameand并更新物件。valuefor..of
const memories = {
email: '',
date: '',
relation: '',
tips: '',
location: '',
};
for (const { name, value } of document.querySelectorAll('input')) {
memories[name] = value;
}
console.log(memories);
<input name="email" value="[email protected]" />
<input type="text" name="date" value="1.1.1970" />
<input type="text" name="relation" value="father" />
<input type="text" name="tips" value="tip" />
<input name="location" value="World" />
您也可以使用該NodeList.forEach()方法代替for..of:
const memories = {
email: '',
date: '',
relation: '',
tips: '',
location: '',
};
document.querySelectorAll('input')
.forEach(({ name, value }) => {
memories[name] = value;
});
console.log(memories);
<input name="email" value="[email protected]" />
<input type="text" name="date" value="1.1.1970" />
<input type="text" name="relation" value="father" />
<input type="text" name="tips" value="tip" />
<input name="location" value="World" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485966.html
標籤:javascript 数组 目的 特性 核心价值
上一篇:帶有陣列到陣列的打字稿物件
