[英]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.