Javascript 你能从嵌套函数中断开一个循环吗?
我有一个Javascript 你能从嵌套函数中断开一个循环吗?,javascript,function,loops,optimization,break,Javascript,Function,Loops,Optimization,Break,我有一个for循环,它重复一个查询函数来遍历数组。有时,查询在循环完成之前到达数组的末尾,导致循环继续运行查询函数时出现多个未定义的返回 我当前的解决方案是在查询函数内部检查undefined,然后在查询函数返回undefined时中断循环: const arr = [...]; function query(index, array) { if (array[index] == null) return return array[index]; } for (let i =
for
循环,它重复一个查询函数来遍历数组。有时,查询在循环完成之前到达数组的末尾,导致循环继续运行查询函数时出现多个未定义的返回
我当前的解决方案是在查询函数内部检查undefined,然后在查询函数返回undefined时中断循环:
const arr = [...];
function query(index, array) {
if (array[index] == null)
return
return array[index];
}
for (let i = 0; i < 10; i++) {
if (query(i, arr ) === undefined)
break;
}
当我尝试此操作时,控制台会记录未捕获的语法错误:非法中断语句
。我知道这是因为中断发生在query()
函数的上下文中,而不是循环中,但是有没有一种方法可以让我向上发送break
以在循环级别进行评估?或任何其他实现此功能的方法?函数查询(索引、数组){
function query(index, array) {
if (array[index] == null)
return false
return (array[index]);
}
for (let i = 0; i < 10; i++) {
if (!query(i, arr ))
break;
}
if(数组[索引]==null)
返回错误
返回(数组[索引]);
}
for(设i=0;i<10;i++){
如果(!查询(i,arr))
打破
}
您可以在循环之前清洁阵列:
让arr=[1,null,2,3,4,5,6,null,未定义,false,0,0,10];
arr=arr.filter((a)=>!!a);
控制台日志(arr)代码>以下是我将如何处理它,我将我的解释写为注释
function query(index, array) {
const value = array[index] ?? false; // I'm, checking if the array item is undefined or nullish using the nullish coalescing operator
if (!value && +value != 0) return; // I'm checking to ensure the item isn't 0, because 0 is also falsy and returning undefined
return array[index];
}
for (let i = 0; i < 10; i++) {
const result = query(i, array);
if (result == undefined) break; // Checking if the function returns undefined and breaking the loop if true
else console.log(result);
}
函数查询(索引、数组){
const value=array[index]??false;//我正在检查数组项是否未定义或是否使用null合并运算符为null
如果(!value&&+value!=0)返回;//我正在检查以确保该项不是0,因为0也是falsy并且返回未定义
返回数组[索引];
}
for(设i=0;i<10;i++){
常量结果=查询(i,数组);
if(result==undefined)break;//检查函数是否返回undefined,如果返回true则中断循环
else console.log(结果);
}
Uh,为什么不直接使用array.find(x=>x!=null)
而不是制作自己的版本呢?@VLAZ因为我的用例实际上不是一个数组,而是我用querySelector('.class')选择的DOM元素。array.from(document.querySelectorAll(“.class”)
?另外,我假设你的条件不是!=null
,因为这对.querySelectorAll()
中的项没有任何意义。您可以使用其他CSS选择器选项来进一步缩小返回列表的范围,使其精确到您想要的范围。我不知道真正的逻辑是什么,但如果它是,比如说,一个给定的属性有一些值,有一个CSS选择器。您可以执行文档。querySelector(“.class[someAttribute='uniqueValue']”)将返回单个元素,而无需执行后期筛选。
function query(index, array) {
const value = array[index] ?? false; // I'm, checking if the array item is undefined or nullish using the nullish coalescing operator
if (!value && +value != 0) return; // I'm checking to ensure the item isn't 0, because 0 is also falsy and returning undefined
return array[index];
}
for (let i = 0; i < 10; i++) {
const result = query(i, array);
if (result == undefined) break; // Checking if the function returns undefined and breaking the loop if true
else console.log(result);
}