js怪异的代码无法在浏览器控制台中运行

时间:2020-03-15 12:39:14

标签: javascript

我正在做一个教程。我知道它的真正基础。 此程序可以在他们使用的任何引擎中运行,而不能在浏览器控制台中运行。

这是位

    suspend fun executeCommand(commandArgs: List<String>): ExecuteCommandResult {
        try {
            val process = ProcessBuilder(commandArgs).start()

            val outputStream = GlobalScope.async(Dispatchers.IO) { readStream(process.inputStream) }
            val errorStream = GlobalScope.async(Dispatchers.IO) { readStream(process.errorStream) }

            val exitCode = withContext(Dispatchers.IO) {
                process.waitFor()
            }

            return ExecuteCommandResult(exitCode, outputStream.await(), errorStream.await())
        } catch (e: Exception) {
            return ExecuteCommandResult(-1, "", e.localizedMessage)
        }
    }

    private suspend fun readStream(inputStream: InputStream): String {
        val readLines = mutableListOf<String>()

        withContext(Dispatchers.IO) {
            try {
                inputStream.bufferedReader().use { reader ->
                    var line: String?

                    do {
                        line = reader.readLine()

                        if (line != null) {
                            readLines.add(line)
                        }
                    } while (line != null)
                }
            } catch (e: Exception) {
                // ..
            }
        }

        return readLines.joinToString(System.lineSeparator())
    }

就像我说的那样,它不会运行。错误: 重复未定义

3 个答案:

答案 0 :(得分:3)

repeat不是独立功能。它仅用于字符串(例如"hi".repeat(3)

您需要首先为您的用法定义repeat

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

let labels = [];
repeat(5, i => {
  labels.push(`Unit ${i + 1}`);
});
console.log(labels);

答案 1 :(得分:1)

repeat不是全局函数,您应该这样做

let labels = [];
for(let i = 0; i < 5; i++) {
  labels.push(`Unit ${i + 1}`);
}
console.log(labels);

答案 2 :(得分:0)

JavaScript本身没有repeat函数。

您必须使用以下循环语句之一来实现指令的重复:

  • for
  • while
  • do - while

FOR

let labels = [];

for(let i = 0; i < 5; ++i) {
  labels.push(`Unit ${i + 1}`);
}

console.log(labels);

何时

let labels = [];

let i = 0;
while(i < 5) {
  labels.push(`Unit ${i + 1}`);
  i++;
}

console.log(labels);

要做-

let labels = [];

let i = 0;
do {
  labels.push(`Unit ${i + 1}`);
  i++;
} while (i < 5);

console.log(labels);