尝试将输入变量值返回到其初始全局变量时的基本问题

时间:2018-07-09 21:59:55

标签: javascript function return

我有以下问题,其中包括无法返回用作函数输入参数的变量值。

该功能本身完全可以正常工作。

但是在函数中计算完后,它无法将修改后的值传递回其全局变量以供进一步使用...而且我无法找出一种动态的方式来完成这项工作。

这是我现在正在使用的代码:

var $value_1 = "100.000"; // Initial Value
var $value_2 = "200.000"; // Initial Value
var $value_3 = "300.000"; // Initial Value

function_1($value_1); // Expected: "100.00"
function_1($value_2); // Expected: "200.00"
function_1($value_3); // Expected: "300.00"

// Failure in returning any values back to its variable despite being calculated in the function
alert($value_1); // Actual: "100.000"
alert($value_2); // Actual: "200.000"
alert($value_3); // Actual: "300.000"

function function_1($recieved_raw_value) // Example: "500.000" becomes "500.00"
        {
            var $parts = $recieved_raw_value.split('.');
            var $loc = $parts.pop();
            var $before_text = $parts.join('.');

            var $after_text = $recieved_raw_value.split('.').pop();

            if($after_text.length > 2) {
                $after_text = $after_text.slice(1,3);

                $recieved_raw_value = $before_text + "." + $after_text;
            } else {
                $recieved_raw_value = $before_text + "." + $after_text;
            }
            return $recieved_raw_value; // Not working to any of the 3 variables...
        }

1 个答案:

答案 0 :(得分:1)

尝试$value_1 = function_1($value_1);

返回数据不会更改您必须为其分配的输入变量。

或者如果您真的想在函数中编辑全局(我建议不要这样做,因为这通常是不好的做法),而不是返回任何内容……

$value_1 = $recieved_raw_value