1) { var z = y[1-6ren">
gpt4 book ai didi

Javascript 函数无法正常工作的问题(它将分数转换为小数)

转载 作者:行者123 更新时间:2023-12-02 16:25:51 25 4
gpt4 key购买 nike

假设我有一个字符串(如分数);

var num = "1/2";

为什么这有效:

var y = num.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
num = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
num = a;
}
}

alert(num); //The alert box shows my variable now as a decimal.

这不会:

function parseFractions(x) {
var y = x.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
x = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
x = a;
}
}
}

parseFractions(num); //Here I call my function.

alert(num);
//The alert box does not even show up. The fraction isn't converted into a decimal.

这基本上是相同的事情,唯一的区别是在第二个中我尝试将其变成一个函数,这样我就不必每次尝试将分数转换为小数时都重复这些代码行。

那我做错了什么?我想要通过函数实现的目标是否可行?感谢任何对此问题的了解!

最佳答案

num 的值没有更新,它不是通过引用传递的。

function parseFractions(x) {
var y = x.split(' ');
if (y.length > 1) {
var z = y[1].split('/');
var a = (+y[0] + (z[0] / z[1]));
x = a;
} else {
z = y[0].split('/');
if (z.length > 1) {
a = (z[0] / z[1]);
x = a;
}
}
return x;
}

num = parseFractions(num); //set num with the value return from the method
alert(num);

关于Javascript 函数无法正常工作的问题(它将分数转换为小数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com