Boolean Javascript - javascript

Javascript beginner here, I keep getting a wrong answer to this question:
"First, figure out if we have enough slices now. Use a comparison operator to figure out if there are enough. Assign the result to the enoughSlicesNow variable."
//Variables are below//
var cakes = 5;
var slicesPerCake = 6;
var attendees = 60;
var bakers = 3;
var cakeBakingTime = 1;
var hoursLeftUntilParty = 5;
This is what I tried but it will not accept:
(cakes * slicesPerCake)>= attendees
var enoughSlicesNow = false

Looks like you need:
var enoughSlicesNow = (cakes * slicesPerCake) >= attendees;

You can do like this using ternary operator
var cakes = 5;
var slicesPerCake = 6;
var attendees = 60;
var bakers = 3;
var cakeBakingTime = 1;
var hoursLeftUntilParty = 5;
var enoughSlicesNow = (cakes * slicesPerCake) >= attendees ?true:false
alert(enoughSlicesNow)
DEMO

Do you want like this...
var cakes = 5;
var slicesPerCake = 6;
var attendees = 60;
var bakers = 3;
var cakeBakingTime = 1;
var hoursLeftUntilParty = 5;
var enoughSlicesNow = (cakes * slicesPerCake)>= attendees;
if(enoughSlicesNow ==true){
alert('Enough');
}
else
{
alert('Not enough');
}

Related

How can you add two random variables (with different values) together in Javascript?

This is my code as shown below. My first set is Fibonacci numbers, the second is Lucas Numbers
var f1 = 1;
var f2 = 1;
var f3 = 2;
var f4 = 3;
var f5 = 5;
var f6 = 8;
var f7 = 13;
var f8 = 21;
var f9 = 34;
var f10 = 55;
var f11 = 89;
var f12 = 144;
var l1 = 1;
var l2 = 3;
var l3 = 4;
var l4 = 7;
var l5 = 11;
var l6 = 18;
var l7 = 29;
var l8 = 47;
var l9 = 76;
var l10 = 123;
var l11 = 199;
var l12 = 322;
var num;
var num2;
I have it so that if num = 1, then you add fibonacci, if num = 2, then you add the lucas numbers.
function question(){
num = Math.floor(Math.random() * 2) + 1;
num2 = Math.floor(Math.random() * 2) + 1;
if(num = 1){
document.getElementById("question").innerHTML = "Find the two numbers in the Fibonacci Series which when added together make" + _______ // What goes here?
}
if(num = 2){
document.getElementById("question").innerHTML = "Find the two numbers in the Lucas Series which when added together make" + _______ // What goes here?
}
}
In the blank area, what goes there? I want to put the sum of 2 random variables (as shown above).
To start off, create two arrays holding the numbers as follows :
let fibNums = [1,1,2,3,5,8,13,21,34,55,89,144];
let lucasNums = [1,3,4,7,11,18,29,47,76,123,199,322];
As the next step create a function which can return the sum of two random numbers based on the array
function generateSum(arr, x, y){
console.log(arr[x], arr[y]); // the selected values from the array
return arr[x] + arr[y];
}
Now just call the function with the array name and by generating random index
generateSum(arrayName , Math.floor(Math.random()*arrayName.length), Math.floor(Math.random()*arrayName.length))
Based on your use case
if(num = 1){
generateSum(fibNums , Math.floor(Math.random()*fibNums.length), Math.floor(Math.random()*fibNums.length))
}
if(num = 2){
generateSum(lucasNums , Math.floor(Math.random()*lucasNums.length), Math.floor(Math.random()*lucasNums.length))
}

JavaScript: how to loop by adding the values of variables with 1, 2, 3, ... at the end?

I'm a beginning JavaScript user. I'd like to calculate a score of 15 questions from a program.
What I need:
I put the value I received to JSq1, JSq2, etc. then I add them up and divided by total question and round up a score. I can lay everything in many lines but that does not look efficient. I'm trying to figure out a way to use loop to get all the same result.
Please help.
THANKS
<script language = "JavaScript">
// the following may work
var JSq1 =Varq1score.getValue();
var JSq2 =Varq2score.getValue();
var JSq3 =Varq3score.getValue();
var JSq4 =Varq4score.getValue();
var JSq5 =Varq5score.getValue();
var JSq6 =Varq6score.getValue();
var JSq7 =Varq7score.getValue();
var JSq8 =Varq8score.getValue();
var JSq9 =Varq9score.getValue();
var JSq10 =Varq10score.getValue();
var JSq11 =Varq11score.getValue();
var JSq12 =Varq12score.getValue();
var JSq13 =Varq13score.getValue();
var JSq14 =Varq14score.getValue();
var JSq15 =Varq15score.getValue();
var totalScore = JSq1 + JSq2 + JSq3 + ...
var totalQuestion = 15
var finalScore = parseFloat(totalScore/totalQuestion*100).toFixed(0);
// I'd like to do the following but don't know how to specify JSq1, JSq2, etc in a loop so I don't have to repeat the lines so many times.
var totalQ = 15;
for (i = 0; i <= totalQ ; i++) {
var JSq+[i] = "Varq"+ i + "score.getValue()";
}
for (i = 0; i <= totalQ ; i++) {
var totalScore = totalScore + JSq + [i];
}
...
</script>
1) Build an object all_vars with all the variable. (Here with object shorthand property, { JSq1 } will be equivalent to { JSq1: Varq1score.getValue() }
2) Use Object.values to get values of above object in an array.
3) Use any loop (in this case we are using reduce) to build total score dynamically.
With these slight changes to your current code, you can achieve the result. Check the following sample code.
var JSq1 = 3;
var JSq2 = 3;
var JSq3 = 3;
var JSq4 = 3;
var JSq5 = 3;
var JSq6 = 3;
var JSq7 = 3;
var JSq8 = 3;
var JSq9 = 3;
var JSq10 = 3;
var JSq11 = 3;
var JSq12 = 3;
var JSq13 = 3;
var JSq14 = 3;
var JSq15 = 3;
var all_vars = {
JSq1,
JSq2,
JSq3,
JSq4,
JSq5,
JSq6,
JSq7,
JSq8,
JSq9,
JSq10,
JSq11,
JSq12,
JSq13,
JSq14,
JSq15
};
var totalScore = Object.values(all_vars).reduce((sum, jsq) => sum + jsq, 0);
var totalQuestion = 15;
var finalScore = parseFloat((totalScore / totalQuestion) * 100).toFixed(0);
console.log(finalScore)

JavaScript arithmetic returns unexpected value

Here is a simple JS snippet,
$("#product_code").live('change',function(){
$.ajax({
type:'POST',
url:baseurl+'ajax/getproduct/'+$(this).val(),
success:function(productdetails){
var bill_type = $("#bill_type").val();
var mrp_value = productdetails['mrp_value'];
var quantity = productdetails['quantity'];
$("#product_name").val(productdetails['product_name']);
$("#packing").val(productdetails['packing']);
$("#mrp_value").val(productdetails['mrp_value']);
$("#batch_number").val(productdetails['batch_number']);
$("#manufacturing_date").val(productdetails['manufacturing_date']);
$("#expiry_date").val(productdetails['expiry_date']);
$("#quantity").val(productdetails['quantity']);
switch(bill_type)
{
case 'stockies':
var pts_value = 5; //In percent
var vat = 5; //In percent
var total_value = (mrp_value+(mrp_value*vat/100)-(mrp_value*pts_value/100))*quantity;
break;
case 'pharmacy':
var pts_value = 3; //In percent
var vat = 5; //In percent
var total_value = (mrp_value+(mrp_value*vat/100)-(mrp_value*pts_value/100))*quantity;
break;
case 'replacement':
var pts_value = 0; //In percent
var vat = 0; //In percent
var total_value = 0;
break;
}
$("#pts_value").val(pts_value);
$("#vat").val(vat);
$("#total_value").val(total_value);
}
});
});
And the value i'm getting through JSON AJAX request is,
{"stock_id":"1","product_code":"AG123456","product_name":"Test Product","packing_area":"10x10","bottle_size":"170ml","product_type":"bottle","chemical_contents":"HCL","batch_number":"12","manufacturing_date":"2012-03-12","expiry_date":"2014-03-12","quantity":"4","packing":"Hard","purchase_value":"34","sales_value":"36","mrp_value":"35","status":"0","created_date":"2014-04-27 14:05:17","modified_date":null,"deleted_date":null}
If i print the values separately, it is showing,
var mrp_value = 35;
var quantity = 4;
and the assigned values are,
var pts_value = 5;
var vat = 5;
var total_value = (mrp_value+(mrp_value*vat/100)-(mrp_value*pts_value/100))*quantity;
So, i'm expecting this will execute as follows,
(35 + (35*5/100) - (35*5/100) ) * 4
(35 + (1.75) - (1.75)) * 4
(35 + (0)) * 4
140
But it is returning 1400 as value. Why and where i'm doing the mistake?
In JavaScript, "5" + 0 = "50". Make sure your variables are numbers and not strings.
Use the Number() function to be sure.
See this input:
var pts_value = 5;
var vat = 5;
var mrp_value = 35;
var quantity = 4;
console.log((mrp_value+(mrp_value*vat/100)-(mrp_value*pts_value/100))*quantity);
var mrp_value = '35';
var quantity = '4';
console.log((mrp_value+(mrp_value*vat/100)-(mrp_value*pts_value/100))*quantity);
This gives this output:
c:\it\nodejs>node.exe 01_hello.js
140
1400

I want to add all the values in the field Sum to the field Total but it is not working

Here, sums[i].value is getting right values but when I want to keep a grand total of all Sum, it is failing.
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
Plain HTML is strings, all the way down, and var amounts = document.getElementsByName("Amount"); followed by amounts.value means you now have string values. Since + is also a string operator, JavaScript will happily turn "2"+"4" into "24", which looks like it did maths, but wrong, when in fact it didn't do math at all.
Convert all values that need to be numbers into numbers, first:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
Replace your code with :
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
This should help you.
Remove the .value while adding and multiplying
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}

jQuery Number array, everything above a certain number

I have a pricing array
pricing = new Array();
pricing[1] = 35;
pricing[2] = 60;
pricing[3] = 84;
pricing[4] = 104;
pricing[5] = 120;
pricing[6] = 132;
pricing[7] = 140;
pricing[8] = 144;
pricing[9] = 153;
pricing[10] = 160;
Everything below 10 has a price, everything above 10 will have the same price as ten
It only goes to 20 so what i did originally was just repeat the price for 11 - 20. But thats wasteful, how can I tell me array that everything > 10 = 160
p.s my final version of this is condensed :)
You can leave your array as is and use a function like:
var getPrice = function(arr, index){
return arr[index > 10 ? 10 : index];
}
var pricing = [], i;
pricing.push(35);
pricing.push(60);
pricing.push(84);
pricing.push(104);
pricing.push(120);
pricing.push(132);
pricing.push(140);
pricing.push(144);
pricing.push(153);
for (i = 0; i < 11; i++) {
pricing.push(160);
}
I also made a JSFiddle for this.
#CD was stating that the push function can take multiple items to append to the array. The code would look like this then:
var pricing = [], value = 160;
pricing.push(35);
pricing.push(60);
pricing.push(84);
pricing.push(104);
pricing.push(120);
pricing.push(132);
pricing.push(140);
pricing.push(144);
pricing.push(153);
pricing.push(value, value, value, value, value, value, value, value, value, value, value);
i=10;
while(i--) { pricing[i+10] = 160; }
You missed the first entry in your array (since it is 0 based). I would change it to this:
pricing = new Array(20);
pricing[0] = 35;
pricing[1] = 60;
pricing[2] = 84;
pricing[3] = 104;
pricing[4] = 120;
pricing[5] = 132;
pricing[6] = 140;
pricing[7] = 144;
pricing[8] = 153;
pricing[9] = 160;
Then you can set the last 10 using this:
for(var x = 10; x < pricing.length; x++) {
pricing[x] = pricing[9];
}
Example fiddle.
pricing = new Array();
var arraySize = 100;
pricing[1] = 35;
pricing[2] = 60;
pricing[3] = 84;
pricing[4] = 104;
pricing[5] = 120;
pricing[6] = 132;
pricing[7] = 140;
pricing[8] = 144;
pricing[9] = 153;
for(var x = 10; x < arraySize; x++)
pricing[x] = 160
console.log(pricing);

Categories

Resources