Can somebody help with a simple JavaScript problem:

Can somebody help with a simple JavaScript problem:
0

#1

I’m trying to right a function that takes a wind speed in knots and converts it to Beaufort scale. (http://www.metoffice.gov.uk/guide/weather/marine/beaufort-scale)
Why doesn’t my code work?

Thanks


#3

I have edited this post’s title to refer to the correct language.


#4

Quite right. Thanks.


#5

This still isn’t working, perhaps I need to to use and IF ELSE instead.


#7

Looks like the current code is also always setting beaufort to 12 at the end anyway.


#8

add default before the default statement (beaufort = 12) so that it is an else, and make sure it is inside of the switch statement at the bottom.


#9

I am still learning this language but just taking quick look, I would do if and else if nested statements. It might not be as efficient as other methods, but its what I would do with the limited knowledge that I have taken in. The code would look something like this

   var knots = 3;
var beaufort
$("#windSpeed").html(knots + " knots");
$("#beaufort").html(" 1test");

function getBeaufort(knots) {
if (knots < 1) {
    $("#beaufort").html(0);
} else if (knots > 1 < 4) {
    $("#beaufort").html(2);
} else if (knots > 4 < 20) {
    $("#beaufort").html(20);
} else if (knots > 3) {
    $("#beaufort").html(20);
} else {
   $("#beaufort").html("unscalable");
}}

Of course you would need more if and else if statements there to cover the broad range of numbers but its a basic approach that should work


#10

with such repetetive if and else, it’s more efficient to use a switch statement fyi


#12

Not necessarily you are just testing for the wrong thing in your switch statement. Instead of checking for a range, you can check if an expression evaluates to true.

Example:

var knots = 3;

$("#windSpeed").html(knots + " knots");

function getBeaufort(knots) {
  var beaufort;
  switch(true) {
    case knots < 1:
      beaufort = 0;
      break;
    case knots < 4:
       beaufort = 3;
      break;
  }
  
  $('#beaufort').text(beaufort)
};

If the expression is true then the beaufort will be set to the case


#13

Awesome. Thanks for your help.

It’s so easy (when you know how!).

Result here: http://codepen.io/jamiepyoung/pen/KNaZVb?editors=0011


#14

Looks great! Love what you did with the UI


#15

Thanks for the positive comments iRoachie. :slight_smile: