[英]Javascript: code refactoring to single line instead of multiple line for loop
I am new to react and javascript , trying to refactor my below code to fewer lines: 我是React和javascript的新手,试图将以下代码重构为更少的行:
for (const email of processedData) {
if (validateEmail(email)) {
count++;
if (count === 100) {
break;
}
}
}
processedData is a list of emails, tried using reduce but in reduce i could not break once i have count === 100 已处理数据是电子邮件列表,尝试使用reduce进行操作,但在reduce中,一旦计数=== 100,我就无法中断
Thanks 谢谢
At least the loop body can be compressed easily: 至少循环体可以轻松压缩:
for(const email of processedData) {
if(validateEmail(email) && ++count === 100) break
}
It would be hard to make it even shorter. 很难使其更短。 >_>
> _>
Array.prototype.some will run a function on your array's element until that function returns true. Array.prototype.some将在数组的元素上运行一个函数,直到该函数返回true。
Then you can do something like this : 然后,您可以执行以下操作:
EDIT : single line version of my first suggestion. 编辑 :我的第一个建议的单行版本。
var processedData = ["joe@test.co.uk", "john@test.co.uk", "jack@test.com", "jane@test.com", "amy@test.com"]; var count = 0; processedData.some(email => validateEmail(email) && (++count === 2)); function validateEmail(email) { console.log("validateEmail " + email); return (email.indexOf(".com") > -1); }
Well, if you just want to have an array with 100 items, then this could help. 好吧,如果您只想拥有一个包含100个项目的数组,那么这可能会有所帮助。 Apply .filter() on the data array and then slice it to 100.
在数据数组上应用.filter(),然后将其切成100。
processedData.filter(email => validateEmail(email)).slice(0,100)
I think... it shoud help, but probably is better way to refactor (as always) 我认为...应该有帮助,但可能是重构的更好方法(一如既往)
for(const email of processedData){
if(validateEmail(email) && count != 100) count++
}
How about using below loop? 如何使用下面的循环?
for(let i=0,count=0; i < processedData.length && count<100; i++){
count+=validateEmail(processedData[i])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.