javascript - 如何使用函数调用代替循环跳转?

标签 javascript loops

我目前正在研究如何在 MDN 上的 javascript 中使用“标记”循环并遇到了以下短语。

enter image description here

我知道标记循环有时用于将代码执行转移到几层以上的外部循环。但是我不明白作者所说的“经常可以使用函数调用而不是循环跳转”是什么意思。有人可以给我举个例子吗?

最佳答案

这是一个示例,它在二维数组 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/

相关文章:

javascript - 使用 JSON 数据的 Highcharts 图表空白

java - 需要一些关于代码的一部分的作用的提示

java - sun.java2d.loops.ProcessPath$点

javascript - 在 AngularJS html5mode Express 环境中提供文件下载服务

javascript - 首先在 JavaScript 中使用 for 循环加载最后的记录

javascript - Backbone.js 属性/获取似乎很有趣

python - 将列表中的项目添加到列表中以查找平均值

javascript - 使用 $filter 时,cloneConnectFn 不是函数

python - 如何使用两个For循环(非嵌套循环)

PHP摩尔斯电码转换器