我目前正在研究如何在 MDN 上的 javascript 中使用“标记”循环并遇到了以下短语。
我知道标记循环有时用于将代码执行转移到几层以上的外部循环。但是我不明白作者所说的“经常可以使用函数调用而不是循环跳转”是什么意思。有人可以给我举个例子吗?
最佳答案
这是一个示例,它在二维数组 array
中搜索元素 n
,并在找到时打印坐标:
function searchAndLogCoords(array, n) {
// The "searching" portion of the function
outterLoop:
for (i = 0; i < array.length; i++) {
row = array[i]
for (j = 0; j < row.length; j++) {
// Break out of the "searching" portion of the function,
// and continue on to the "logging" portion
if (row[j] == n) break outterLoop
}
}
// The "logging" portion of the function
console.log("x: " + i + ", y: " + j)
}
var array = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
searchAndLogCoords(array, 1)
下面是相同的代码,通过将“搜索”部分提取到它自己的函数中编写得更好:
searchAndLogCoords(array, 1)
function searchAndLogCoords(array, n) {
for (i = 0; i < array.length; i++) {
row = array[i]
for (j = 0; j < row.length; j++) {
if (row[j] == n) return {x: i, y: j}
}
}
}
function getCoords(array, n) {
var coords = searchAndLogCoords(array, n)
console.log("x: " + coords.x + ", y: " + coords.y)
}
var array = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
searchAndLogCoords(array, 1)
您可以在线尝试,here .
关于javascript - 如何使用函数调用代替循环跳转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616294/