[英]Returning a value from switch statement
I'm new to web development (JS) and I know there are many topics matching the title of mine, but no similar questions were answered, or maybe because I'm newbie, couldn't find. 我是Web开发(JS)的新手,我知道有许多主题与我的标题匹配,但没有回答类似的问题,或者可能是因为我是新手,所以找不到。
In the code below I wanted my function and switch statements, to retrieve values from the arrays (bills) and in order to calculate new value, which to be assigned into a new non-existing place into the array tips
. 在下面的代码中,我希望我的function和switch语句能够从数组(清单)中检索值,并计算出新值,然后将其分配给数组
tips
不存在的新位置。 As a final result I want the function to return tips
array with the value, depending on the case. 作为最终结果,我希望函数根据情况返回带值的
tips
数组。
I know another way for solving this, anyway I was wondering whats wrong here, because that idea for solving
it first came to my mind, and I thought it would work. 我知道解决此问题的另一种方法,无论如何,我想知道这里出了什么问题,因为我首先想到了
solving
这个solving
想法,而且我认为它会起作用。
Here is my code: 这是我的代码:
var tips = [];
var bills = [124, 48, 264];
function tipCalc(bills, tips){
switch(bills){
case bills < 50:
tips[0] = bills[1] * 0.2;
break;
case bills > 50:
tips[1] = bills[0] * 0.5;
break;
default:
console.log('no tips left.');
}
return tips;
}
tips = tipCalc(bills[0]);
console.log(tips);
enter code here
Let's break this code down a bit and talk about what it's doing 让我们将这段代码分解一下,讨论一下它在做什么
var tips = [];
var bills = [124, 48, 264];
This part is declaring two variables in the global scope, which will both be accessible by any functions for both reading and writing (important - Google JS closures). 这部分是在全局范围内声明两个变量,任何函数都可以访问它们以进行读写(重要的-Google JS闭包)。
function tipCalc(bills, tips){
switch(bills){
You have now started a function which calls a switch to evaluate the value of bills. 现在,您已经启动了一个函数,该函数调用一个开关来评估票据的价值。 Because you are passing in
bills[0]
, it will be evaluating bills[0] (124). 因为您要传递
bills[0]
,所以它将评估bills [0](124)。 It also accepts a second parameter called tips, which is undefined because no second argument is passed in when the function is called. 它还接受一个名为tips的第二个参数,该参数是未定义的,因为调用该函数时不会传递第二个参数。
case bills < 50:
tips[0] = bills[1] * 0.2;
break;
This part is broken. 这部分坏了。 If it was changed to an
if
statement, it would evaluate to false. 如果将其更改为
if
语句,则其结果将为false。
case bills > 50:
tips[1] = bills[0] * 0.5;
break;
Also broken. 也坏了。 If changed to
if
statement, it would evaluate to true and be executed, but it would be performing an operation on undefined. 如果更改为
if
语句,它将评估为true并被执行,但是它将对未定义执行操作。 If you didn't h have a second param also named tips
, then you would be setting the global tips
to 62. 如果没有第二个参数,也称为
tips
,则将全局tips
设置为62。
default:
console.log('no tips left.');
}
This is the part that should currently be executed because it is the only one that can be true with the other two cases being structured incorrectly. 这是当前应执行的部分,因为这是唯一可以正确执行的部分,而其他两种情况的结构不正确。
return tips;
}
Will return undefined because tips (within the scope of the function itself) began as undefined and has not been altered. 将返回undefined,因为技巧(在函数本身的范围内)以undefined开头,并且尚未更改。
tips = tipCalc(bills[0]);
console.log(tips);
enter code here
Breaks the whole program, should be a comment with //
at the beginning. 中断整个程序,应以
//
开头的注释。
well, this is not good approach, but if it is required for you to use Switch you can try like this without bills array at all: 好吧,这不是一个好方法,但是如果您需要使用Switch,则可以尝试完全不使用bills数组的方式:
<script type="text/javascript">
var tips = [];
function tipCalc(bill) {
switch (true) {
case (bill < 50):
tips.push(bill * 0.2);
break;
case (bill > 50):
tips.push(bill * 0.5);
break;
default:
console.log('no tips left.');
}
return tips;
}
tipCalc(10);
for (let index = 0; index < tips.length; index++) {
console.log(tips[index]);
}
</script>
Or in case you need to compare bills array and depends to the value insert to tips array i would make it like : 或者,如果您需要比较bills数组,并取决于将值插入tips数组,我会这样:
<script type="text/javascript">
var tips = [];
var bills = [124, 48, 264];
function tipCalc(bills) {
for (let index = 0; index < bills.length; index++) {
if (bills[index] <=50) {
tips.push(bills[index] * 0.2);
}
else if (bills[index] >= 50) {
tips.push(bills[index] * 0.5);
}
else
console.log("no tips left.");
}
}
tipCalc(bills);
for (let index = 0; index < tips.length; index++) {
console.log(tips[index]);
}
</script>
Here's a verbose way of doing what I think you want to do. 这是我想做的详细方法。 (add up the tips total)
(总计小费)
// create a blank tips array which we'll add to later var tips = []; // our bills array var bills = [124, 48, 264]; // create a function that will calculate tips based on the bill totals function calculateTips() { // create a counter that we will use to determine when we've reached the end of the loop var forEachCounter = 0; // for each will loop through each item in the bills array bills.forEach(function(amount) { //this increases the counter by 1 on each loop forEachCounter++; switch(true) { case (amount <= 50): // .push appends to the array tips.push(amount * 0.2); break; case (amount > 50): // amount is the value of the bill for this iteration * 0.5 tips.push(amount * 0.5); break; } // if end of array has been reached // bills.length = the total amount of array items in bills arrat if (forEachCounter === bills.length) { // create a totalTips variable to add to var totalTips = 0; // create another counter to detect when end is reached var forEachCounter2 = 0; // loop through the tips array tips.forEach(function(tipamount) { // add 1 to counter on each loop forEachCounter2++; // add to totalTips // can also do totalTips = totalTips + tipamount; totalTips += tipamount; // when end of tip array is reached.. if (forEachCounter2 === tips.length) { //alert(totalTips); // output it to where you need it document.getElementsByTagName('body')[0].innerHTML = totalTips; } }) } }) } // call it when you need it calculateTips();
note 注意
If you're working with a lot of tips (like an entire national restaurant chain) you may want to consider using if/else instead of switch because switch is demonstrated to be slower with ranges 如果您正在使用许多技巧(例如整个国家级餐厅连锁店),则可能要考虑使用if / else而不是switch,因为事实证明,范围变化会导致开关速度变慢
fiddle with it here 在这里摆弄
https://jsfiddle.net/Hastig/p1kfgreq/ https://jsfiddle.net/Hastig/p1kfgreq/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.