在Javascript中返回两个值 - 返回[foo,bar] vs return foo +“”+ bar

时间:2018-04-12 23:54:21

标签: javascript return

我正在经历一些黑客挑战,这在我的功能中出现了。

返回foo +“”+ bar 的第二种方法给了我一个错误,但第一种方法有效。为什么?返回这两种方法有什么区别?

编辑: - 评论者的利益的完整来源......

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(str => str.trim());

    main();
});

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

/*
 * Complete the solve function below.
 */
function solve(a0, a1, a2, b0, b1, b2) {
    /*
     * Write your code here.
     */
    let aScore = 0;
    let bScore = 0;

    function compare(valA, valB){
        if (valA < valB){
            bScore += 1;
        }
        else if (valA == valB){
        }
        else {
            aScore += 1;
        }
    }

    compare(a0, b0);
    compare(a1, b1);
    compare(a2, b2);
    return [aScore, bScore];

}

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

    const a0A1A2 = readLine().split(' ');

    const a0 = parseInt(a0A1A2[0], 10);

    const a1 = parseInt(a0A1A2[1], 10);

    const a2 = parseInt(a0A1A2[2], 10);

    const b0B1B2 = readLine().split(' ');

    const b0 = parseInt(b0B1B2[0], 10);

    const b1 = parseInt(b0B1B2[1], 10);

    const b2 = parseInt(b0B1B2[2], 10);

    let result = solve(a0, a1, a2, b0, b1, b2);

    ws.write(result.join(" ") + "\n");

    ws.end();
}

1 个答案:

答案 0 :(得分:2)

使用return [aScore, bScore],您将返回包含两个元素的数组,而return aScore + " " + bScore返回单个字符串