我有这个功能,例如:
app.get('/', function(req, res) { var token = req.query.token; if(!token) { res.render('auth'); // Authentication } else { authorizedUsers.forEach(function(user) { if(user.id == token) { console.log('found, nickname: ' + user.nickname); return true; } }); console.log('not found'); return false; } });基本上它循环遍历authorizedUsers数组,并查找entry.id等于token变量的条目。
我想要做的是,如果找到,返回true并停止执行app.get('/')...块的其余部分。
如果没有找到,显然forEach循环已经遍历所有条目,并且最终执行到达“未找到”的打印并return false; 。
对于我当前的代码,即使找到一个条目,执行仍然继续,我仍然得到“未找到”日志。
我错过了什么吗?
为了简化事情,我想做的是:
循环遍历所有authorizedUsers条目,将entry.id与token变量进行比较。 如果找到,请将“找到”打印到控制台并停止执行。 如果未找到,请将“未找到”打印到控制台并停止执行。谢谢。
编辑
按照Michael的解决方案,这是我的工作代码:
app.get('/', function(req, res) { var token = req.query.token; if(!token) { res.render('auth'); // Authentication } else { if(!authorizedUsers.some(function(user) { if(user.id == token) return true; })) { console.log('No entries found.'); } else { console.log('Entries found!'); } } });I have this function, for example:
app.get('/', function(req, res) { var token = req.query.token; if(!token) { res.render('auth'); // Authentication } else { authorizedUsers.forEach(function(user) { if(user.id == token) { console.log('found, nickname: ' + user.nickname); return true; } }); console.log('not found'); return false; } });Basically it's looping through the authorizedUsers array, and looking for an entry where entry.id equals the token variable.
What I wanted to do is, if found, to return true and stop the execution of the rest of the app.get('/')... block.
If not found, obviously the forEach loop has already gone through all entries, and eventually the execution arrives to the printing of "not found" and return false;.
For my current code, even though an entry is found, execution continues and I still get the 'not found' log.
Am I missing anything?
To simplify things, what I wanna do is:
Looping through all authorizedUsers entries, comparing entry.id to the token variable. If found, print "found" to the console and stop the execution. If not found, print "not found" to the console and stop the execution.Thank you.
Edit
Following Michael's solution, this is my working code:
app.get('/', function(req, res) { var token = req.query.token; if(!token) { res.render('auth'); // Authentication } else { if(!authorizedUsers.some(function(user) { if(user.id == token) return true; })) { console.log('No entries found.'); } else { console.log('Entries found!'); } } });最满意答案
你可以使用Array.prototype.some :
authorizedUsers.some(function(user) { return user.id == token; }some()方法测试数组中的某个元素是否通过了由提供的函数实现的测试。
You would use Array.prototype.some for this:
authorizedUsers.some(function(user) { return user.id == token; }The some() method tests whether some element in the array passes the test implemented by the provided function.
更多推荐
发布评论