[英]Changing for loop to use forEach in javascript
For my project, I have a list of students and am meant to use super basic regular expressions to check their grades. 对于我的项目,我有一个学生列表,我打算使用超级基本正则表达式来检查他们的成绩。 The A and B students are to be added to separate arrays for only those students.
A和B学生将被添加到单独的阵列中,仅适用于那些学生。 The code for doing so is as follows:
这样做的代码如下:
const aTest = new RegExp(/(A)/i);
const bTest = new RegExp(/(B)/i);
const aStudents = [];
const bStudents = [];
for (var i = 0; i < students.length; i++) {
if (aTest.test(students[i].grade)) {
aStudents.push(students[i]);
}
if (bTest.test(students[i].grade)) {
bStudents.push(students[i]);
}
}
However, if I were to use forEach instead of a for loop, how should I go about doing so? 但是,如果我使用forEach而不是for循环,我应该怎么做呢?
You just need to change every students[i]
to the first parameter provided to the forEach
(which references the current item being iterated over in the array), probably call it student
: 你只需要将每个
students[i]
更改为提供给forEach
的第一个参数(它引用在数组中迭代的当前项目),可能称之为student
:
students.forEach(student => {
if (aTest.test(student.grade)) {
aStudents.push(student);
} else if (bTest.test(student.grade)) {
bStudents.push(student);
}
});
But if you have a regular expression literal already, there's no need for new RegExp
- just assign the regular expression literal to the variable. 但是如果你已经有一个正则表达式文字,则不需要
new RegExp
- 只需将正则表达式文字指定给变量即可。 Also, there's no need for a captured group if you just need to test
: 此外,如果您只是需要
test
,则不需要捕获的组:
const aTest = /A/i;
const bTest = /B/i;
Or, you might avoid regular expressions entirely and use (ES6) .includes
instead: 或者,您可以完全避免使用正则表达式并使用(ES6)
.includes
:
if (student.grade.includes('A')) {
aStudents.push(student);
} else if (student.grade.includes('B')) {
bStudents.push(student);
}
I would use filter
instead of forEach
, yes it loops over the array twice but the code is clearer to read and understand 我会使用
filter
而不是forEach
,是的,它会在数组上循环两次,但代码更清晰,可以阅读和理解
const aStudents = students.filter(student => student.grade.match(/A/i));
const bStudents = students.filter(student => student.grade.match(/B/i));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.