从函数返回多个值

时间:2014-12-06 00:34:00

标签: javascript jquery arrays

我有一个js文件(下面),其中每个函数返回2个结果(Step1和Step2)。我需要将这些结果放到像...这样的格式中。

“混合”+(Step1 productType)+“with”+(Step1 peroxide)+“。”+(Step1计时)

使用“+(Step2 productType)+”,将“+(Step2 toneCalc)+”与“+(Step2 peroxide)+”混合。 “+(Step2计时)

将这些结果转换为上述格式的最佳方法是什么? 我知道如何处理单个值,但对函数中包含的多个函数不太确定。

由于

function doubleprocess(type) {

   function productType() {
    var step1;
    var step2;
    if (type == "light") {
        step1 = "lightner";
        step2 = "demi-color";
    } else {
        step1 = "demi-color";
        step2 = "demi-color";
    }
    return step1, step2;
   }


   function toneCalc() {
    var step1;
    var step2;

    if (type == "light") {
        step1 = "light gold";
    } else if (type == "dark") {
        step1 = "80% gold with 20% red"
    } else {
        step1 = "another tone";
    }

    step2 = "neutral";

    return step1, step2;
   }

   function peroxide() {
    var step1;
    var step2;

    if (type == "light") {
        step1 == "20V/6% peroxide";
    } else if (type == "dark") {
        step1 = "something else";
    } else {
        step1 = "Do something.";
    }
    step2 = "Do something else.";
    return step1, step2;
   }

   function level() {
    var step1 = "";
    var step2;

    if (type == "dark") {
        step1 = "Do something.";
    } else {
        step1 = "Do Nothing.";
    };

    step2 = "Do something.";

    return step1, step2;
   }

   function timing() {
    var step1;
    var step2;
    if (type == "light") {
        step1 == "Do something.";
        step2 = "Do something.";
    } else if (type == "dark") {
        step1 = "Do something.";
        step2 = "Do something.";
    } else {
        step1 = "Do something.";
        step2 = "Do something.";
    }
     return step1, step2;
   }
 }

2 个答案:

答案 0 :(得分:3)

您无法从函数返回多个变量。但是你可以返回一个对象。

function peroxide() {
    var step1;
    var step2;

    if (type == "light") {
        step1 == "20V/6% peroxide";
    } else if (type == "dark") {
        step1 = "something else";
    } else {
        step1 = "Do something.";
    }
    step2 = "Do something else.";
    var rtn = new Object();
    rtn.step1 = step1;
    rtn.step2 = step2;
    return rtn;
   }

答案 1 :(得分:1)

Javascript函数只返回一个值。尝试返回一个对象或数组。