Javascript编程功能 [英] Javascript programming functions

查看:92
本文介绍了Javascript编程功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有接收电话的功能

If i have a function that receives a call like

function car_total(y) {

final_total(y);
}


function toy_total(x) {

final_total(x);
}

我如何创建一个计算两个总数的函数,如果它们存在但只能接收1参数而不抛出错误,这可能吗?

How can I make a function that computes both totals if they exist but can only receive 1 parameter and not throw an error, is this possible?

function final_total(x,y) {
//if passed just x
sum = x ;
//if passed just y 
sum = y;
//if passed x, y 
sum = x + y ; 

}


推荐答案

你可以只传递一个参数,但只有一个参数,参数必须是 x ;因为没有办法(没有传递一个对象)确定你想要传入哪个变量。因此收到的第一个变量将始终是 x ,第二个 y ,但是,我建议:

You can pass only one argument, but with only one argument that argument must be x; as there's no way (without passing an object) of determining which variable you 'meant' to pass in. Therefore the first variable recieved will always be x, the second y, that said, though, I'd suggest:

function final_total(x,y) {
    return y ? x + y : x;
}

并且,在只有一个传入参数的情况下,此函数返回单个值或给定两个变量返回这两个变量的总和。即使没有办法确定 x y 被传入。

And, in the presence of only one passed-in argument this function returns that single value or, given two variables, returns the sum of those two. So this does do as you want, even if there's no way to ascertain whether x or y was passed-in.

但是,如果你必须明确传入 x y (由于某种原因):

If, however, you must explicitly pass in either x or y (for some reason):

function final_total(values) {
    var x = values.x || 0,
        y = values.y || 0;
    return x + y;
}

var variableName1 = final_total({x : 23, y : 4});
console.log(variableName1);
// 27

var variableName2 = final_total({y : 4});
console.log(variableName2);
// 4

var variableName3 = final_total({x : 23});
console.log(variableName3);
// 23​

JS小提琴演示

这篇关于Javascript编程功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆