[英]How to skip a loop after checking existence in an object in JavaScript
我有以下脚本:
var done = {'foo':1};
var mylist = ['foo','bar','qux'];
mylist.forEach(function(val) {
// This if condition doesn't work
if (val in done) { continue;}
console.log(val)
});
它的作用是循环遍历mylist
并检查是否已存在done
的成员,请跳过打印。
但是我的代码给出了以下错误消息:
Uncaught SyntaxError: Illegal continue statement(…)
预期的结果是这样的:
bar
qux
什么是正确的方法?
continue
在forEach
不起作用,因为您可以在cursor.forEach()中看到“继续” 。 您可以使用return
而不是continue
。
您可以使用hasOwnProperty
来检查对象是否具有属性。
var done = { 'foo': 1 }; var mylist = ['foo', 'bar', 'qux']; mylist.forEach(function(val) { // This if condition doesn't work if (!done.hasOwnProperty(val)) { console.log(val); document.write(val + '<br />'); } });
只需颠倒条件中的逻辑:
var done = { foo: 1 }, mylist = ['foo', 'bar', 'qux']; mylist.forEach(function (val) { if (!(val in done)) { document.write(val + '<br>'); } });
或使用return
跳过功能流程
var done = { foo: 1 }, mylist = ['foo', 'bar', 'qux']; mylist.forEach(function (val) { if (val in done) { return; } document.write(val + '<br>'); });
如果希望以更具可读性的方式使用Array的filter
和Object.keys
可以使用它:
var done = {'foo':1};
var mylist = ['foo','bar','qux'];
// Utility function
var has = function(obj, prop) {
return Object.keys(obj).indexOf(prop) !== -1;
};
// Get missing values
var missingValues = mylist.filter(function(val) {
return !(has(done, val));
});
// Print each of them
missingValues.forEach(function(val) {
console.log(val);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.