Javascript 函数不工作的问题(它将分数转换为小数)
Javascript problems with a function not working (it converts fractions into decimals)
假设我有一个字符串(如分数);
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);
你需要return你的价值
在函数末尾添加一个 return
return x;
然后用
调用函数
alert(parseFractions(num)); //Here I call my function.
假设我有一个字符串(如分数);
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);
你需要return你的价值
在函数末尾添加一个 return
return x;
然后用
调用函数alert(parseFractions(num)); //Here I call my function.