为什么我在黑客等级 nodejs 中收到 ~ 标准输出没有响应 ~

Sam*_*uel 4 node.js

请谁知道如何在hackerrank上使用stdin和stdout运行函数

function getPrimes(n){

nextPrime:
for (let i = 2; i <= n; i++) { // for each i...

  for (let j = 2; j < i; j++) { // look for a divisor..
    if (i % j == 0) continue nextPrime; // not a prime, go next i
  }

 console.log(i) ; // a prime
}
}
Run Code Online (Sandbox Code Playgroud)

然后使用过程。用于显示结果的 stdin 和 stdout 函数

Mun*_*eeb 15

Hackerrank 文档没有提到这一点。

这就是它对我的工作方式。

// It will work on Javscript(nodejs), not sure about others
fs.createWriteStream(process.env.OUTPUT_PATH).write("Your Output");
Run Code Online (Sandbox Code Playgroud)


Cer*_*nce 5

看看你正在编写的函数是如何被使用的。例如,使用,在 HackerRank内置getPrimes代码中查找 的其他用途。例如,从示例测试中,有一个问题要求我完成一个功能:getPrimesfindNumber

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}



// Complete the findNumber function below.
function findNumber(arr, k) {

}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const arrCount = parseInt(readLine().trim(), 10);

    let arr = [];

    for (let i = 0; i < arrCount; i++) {
        const arrItem = parseInt(readLine().trim(), 10);
        arr.push(arrItem);
    }

    const k = parseInt(readLine().trim(), 10);

    const res = findNumber(arr, k);

    ws.write(res + '\n');

    ws.end();
}
Run Code Online (Sandbox Code Playgroud)

该函数findNumber正在行中被调用

const res = findNumber(arr, k);
Run Code Online (Sandbox Code Playgroud)

其返回值分配给res. 如果使用被调用函数的返回值,您可能应该始终返回一个 value。否则,如果它没有被使用,例如,如果该线路只是

findNumber(arr, k);
Run Code Online (Sandbox Code Playgroud)

那么返回值将被忽略,因此您的输出可能取决于您的调用内容console.log

就您而言,您可能应该提供 return一个值,getPrimes以便 HR 可以解析它。不确定挑战要求什么,但也许是这样的

function getPrimes(n) {
  const arrOfPrimes = [];
  nextPrime: for (let i = 2; i <= n; i++) { // for each i...

    for (let j = 2; j < i; j++) { // look for a divisor..
      if (i % j == 0) continue nextPrime; // not a prime, go next i
    }

    arrOfPrimes.push(i);
  }
  return arrOfPrimes;
}
Run Code Online (Sandbox Code Playgroud)

或类似的东西 - 只要确保return最后有东西被编辑,如果调用的结果getPrimes正在某处使用。