gpt4 book ai didi

javascript - 带有对象的数组上的 .forEach 将不会运行

转载 作者:行者123 更新时间:2023-11-28 14:27:10 26 4
gpt4 key购买 nike

所以现在我正在开发一个系统,学生可以将他们的分数放入表单中,该表单将运行一个函数,该函数将所有标记作为对象放入数组中。

例如:{english_period1: 10, english_period2: 7} <示例

但是,如果我想运行 array.prototype.forEach 来对数组内的标记执行某些操作。它绝对没有返回任何内容。 .forEach 甚至不会运行。

这是脚本:

// Make new variable which will store the marks
let allMarks = [];

document.querySelector("#marks").addEventListener('submit', e => {
e.preventDefault();

//Execute for each input
for(let i = 0; i < e.srcElement.length-1; i++){
// Assign name and value
const name = e.srcElement[i].name;
const value = e.srcElement[i].value;

//Check if value is a mark (number)
if(value % 1 == 0 && value <= 10){
//Assign mark
allMarks[name] = value;
}else{
//Value is not a mark, check if it's a O, V or G
if(value == "O" || value == "V" || value == "G"){
allMarks[name] = value;
}else{
console.log("Niet toegestaan");
}
}
}

allMarks.forEach(mark => {
console.log("hello world");
});

},false);

它的作用是:

  1. 用户输入标记并点击并提交表单后
  2. 遍历表单中的所有输入,并将名称和值作为对象放入数组中。
  3. 检查数组中的每个内容并在控制台中打印“hello world”。

该脚本的目标是计算学生的平均成绩,并根据某些规则进行检查,看看他们是否通过了学年。

我做错了什么?是否可以在包含对象的数组上使用 array.prototype.forEach ?我该如何优化这段代码?

提前致谢!

答案

而不是使用:allMarks[name] = value,它不会将项目添加到数组allMarks = []。使用 allMarks.push({name: name, value: value}); 就可以了。因为现在它将在数组中添加一个项目(对象),因此 forEach 可以循环每个项目并像普通对象一样获取它的值。

特别感谢:@mhodges

长答案

因此,在调试后,编写了更多脚本,我得出的结论是,按照下面答案中的建议使用对象是一个更好、更漂亮的选择。

可以使用objectName[variableName]动态地将键添加到对象。通过使用Object.keys(objectName),您可以将键放入数组中并循环遍历键。它将(就我而言)产生更漂亮的数据结构:

而不是:[{field: "English", period: "period_1", mark: "7.5"}]这将返回:

"English": {
"period_1": 7.5,
"period_2": 6.4
}

最佳答案

请注意,很难说出您到底想在这里做什么。如果您需要 allMarks 是一个数组,那么您需要将每个单独的mark 添加到allMarks数组,如下所示:

// Make new variable which will store the marks
let allMarks = [];

document.querySelector("#marks").addEventListener('submit', e => {
e.preventDefault();

//Execute for each input
for(let i = 0; i < e.srcElement.length-1; i++){
// Assign name and value
const name = e.srcElement[i].name;
const value = e.srcElement[i].value;
// <-- create new mark object -->
const newMark = {name: value}

//Check if value is a mark (number)
if(value % 1 == 0 && value <= 10){
//Assign mark
//<-- instead of allMarks[name] = value; -->
//<-- you need to add the newMark to the allMarks array -->
allMarks.push(newMark);
}else{
//Value is not a mark, check if it's a O, V or G
if(value == "O" || value == "V" || value == "G"){
//<-- same thing here -->
allMarks.push(newMark);
}else{
console.log("Niet toegestaan");
}
}
}

allMarks.forEach(mark => {
console.log("hello world");
});

},false);

但是,您可以将 allMarks 设为一个对象,然后将每个单独的 mark 设置为该对象的键值对。您仍然可以循环访问对象中的键值对,但无法使用 .forEach

你更喜欢哪一个?

关于javascript - 带有对象的数组上的 .forEach 将不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com