Issue in simple JavaScript "Web App" [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working on a little project. It is about solving a math riddle. You can find the repo here: https://github.com/soulwash/how-many-soldiers
The problem occurs when I enter a number and click "Try". After I have done so I want to use the Buttons "Add +1", "Add +7" or "Next Higher Solution". The problem is that it is not just adding numbers but instead adding it at the end of the number creating a way higher amount.
For example:
Entering 290 -> then clicking Try -> then clicking "Add +1" -> it ends up with 2901 instead of 291
Same is with +7 and "Next Higher Solution" but not with the subtracting options.
Can you help me solve this issue?
Thanks!!

JavaScript auto convert data-type into string if first value is string. ex :
var x = "5" + 2 + 3; // output : 523
var x = 5 + 2 + "3"; // output : 73
var x = 5 + 2 + 3; // output : 10
so check value again the " + operator " work with two type
1) add
2) concatenate the string
Best of Luck :)

It sounds like you have your starting value as a string and trying to add to the string. When you add a number to a string you concatenate the string with that number ("71" + 6 becomes "716"). This is because + acts as addition and concatenation depending on how/when it's used. However, - acts differently. When you subtract JavaScript does a quick conversion of types and it does a numeric difference ("716" - 6 becomes 710 with 710 now being a type of number). Below is a quick example:
var st = "71";
st = st + 6;
console.log(st);
console.log(typeof st);
st = st - 6;
console.log(st);
console.log(typeof st);

In file /src/app/howmanysoldiers.js line 43 you use let userInput = document.getElementById("userInput").value, but this is a string. Whats happening is like code bellow:
console.log('10' + 1) // '101'
console.log('10' - 1) // 9
To solve this situation you can try 2 different approaches
Using parseInt
let userInput = parseInt(document.getElementById("userInput").value) // And now it is a number
Subtracting the value
let userInput = document.getElementById("userInput").value - 0 // And now it is a number

Related

Logic for my land size calculator application

I'm making this acres and karats calculator for my uncle to help him in his work.
I'll explain the whole idea of this thing with this example. So if you add 3.22 + 2.2 it should be = 5.42 but in this calculator 3.22 + 2.2 should = 6, because 3 acres + 2 acres = 5 acres and 22 karats + 2 karats = 1 acre, so the total would be 6 acres.
The way I'm doing it in the code is that I'm splitting a number like 3.22 to two, 3 and 22 and the other number to 2 and 2 and I add the whole numbers together and the fractions together and if the fractions are >= 24 I add one to the whole numbers and if there're fractions left from the whole calculation I leave it. For example 3.15 + 2.15 = 6.6, but I'm stuck on how I can add the numbers, there's also an error in there that I don't know how to resolve.
Anyway here's the code
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
function getTotal() {
d += Math.floor(num);
p += getValue(num);
if (p >= 24) {
p -= 24;
++d;
}
total = d + p / 100;
ptag.textContent = total;
}
I added the part of the code where I'm stuck.
Note: I'm trying to make the thing able to add multiple numbers not only two. Also I'm trying to add subtraction but I have no idea how to start working on the subtraction because I haven't even finished the addition.
If the error you are talking about is something like this:
Uncaught TypeError: Cannot read property '1' of null
It is because of your getValue function.
My suggestion is, instead of using something as complicated as
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
use
function getValue(v) {
return floor((v % 1) * 100);
}
This has the same effect as the code you wrote. Which for example, from input 3.13, returns 13.
But there are few other problems.
First, you should update your num variable every now and often, otherwise, it is always going to stay as an empty string (you only defined it on line 20, and you didn't update it after that).
Second, you should clear the d and p variable after you use. As of right now, both of these variables just keeps on increasing every time you run the getTotal function
For your question of how you can add two numbers, I suggest you to create a variable where you can store the first number that the user typed.
For example, when the user typed in 4.19 and pressed the plus button, save that 4.19 into a variable (let's say firstNum).
Then when the user pressed equal button, add the number from the current input field with the firstNum variable.
On how exactly you are going to add two different numbers, break two numbers you want to add into Acres part and Karats parts. Then add them separately, then use your getTotal.
So if the number is 3.21 and 5.18, add 3 and 5, add 21 and 18, then add both of them.
you'll get 8.39. Finally, convert 8.39 into 9.15.
Sorry if my calculation is not correct. It is my first time with this concept!
But I believe this is the way to go.

Algorithm to obtain the item(s) at a precise number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I find that algorithm/functionality in two games already, but I always wanted to know what was the logic behind it.
Basically, there is a list of items and each of them has an id.
For example:
item_1 has id: 1
item_2 has id: 2
item_3 has id: 4
item_4 has id: 8
item_5 has id: 16
etc.
The id is multiplied by two every new item.
There is then a number, let's say 4, that indicate what the current item is. Is this case that would be item_3, but the tricky part is that number could also select multiple items at once like 7 which is 4 + 2 + 1 (item_3, item_2, item_1) or 17 which is 16 + 1 (item_5, item_1). It can go really high like 16384 if you have a long list and still be perfectly accurate for the multiple selections.
How do I solve this problem?
The algorithm you described is basically outputting where the 1's are in the binary representation of the number.
For 7, its binary representation is 111. There are three 1's: in the first, second, and third position from the left respectively, so it's item 1, 2 and 3. Note that we are counting from the left.
Another example:
For 10, its binary representation is 1010. There are two 1's: in the second and fourth position from the left, so the output would be items 2 and 4.
Here is an implementation in C#.
public static List<int> FindOnes(int number) {
var list = new List<int>();
var binaryString = Convert.ToString(number, 2);
for (int i = 0 ; i < binaryString.Length ; i++) {
if (binaryString[binaryString.Length - i - 1] == '1') {
list.Add(i + 1);
}
}
return list;
}
// usage:
FindOnes(7) // [1,2,3]
No idea how the games you're talking about implement it, but if this was me I would do it using bits in the binary expression of the number (example code in java).
public boolean isItemSelected(final int number, final int itemId) {
return (number & (1 << (itemId - 1))) != 0;
}
The trick here being that the binary representation of a number (from right to left) already denotes whether 1, 2, 4, 8, 16, etc. is required additively to make the number using only powers of two. The left shift simply makes a number which (in binary) is all 0's except a 1 in the 'itemId - 1'th slot. The & will match if that bit is 1 in the given number. And then checking that the result is not 0 simply turns it into a boolean.
Obviously you can combine this with some looping or anything else if you want to build the array/List of all the 'itemIds' which match.
In Javascript, you could take the number, convert it to a binary value, take the bits, reverse it and take the values (index plus one) or zero for a filtering of truthy values.
var value = 13,
items = [...value.toString(2)].reverse().map((v, i) => +v && (i + 1)).filter(Boolean);
console.log(items);

Getting wrong output when trying to loop through the first 50 even Fibonacci numbers in JavaScript [duplicate]

This question already has answers here:
Javascript looping through Fibonacci numbers and testing for even numbers
(2 answers)
Closed 8 years ago.
I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.
I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”
I needed to:
1. create a loop that generates Fibonacci numbers.
2. test each one for whether it's even or odd.
3. Add up up the even ones, counting them as you go.
------------HERE IS MY CODE THUS FAR --------
<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is:
<span class="" id="sumFibResult"></span>
<script>
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function () {
fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum() {
var loopFib;
//Initialize fibonacci array
var fibonacci = new Array();
//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum = 0;
//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
for (loopFib = 2; loopFib <= 150; loopFib++) {
// Next fibonacci number = previous + one before previous
fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];
//test for even numbers with if then statement
var integer = parseInt(fibonacci[loopFib]);
if (integer % 2 == 0) {
//Add up the even fib numbers if even and output into dispay variable
var display = sum += fibonacci[loopFib];
//output results to html page
document.getElementById("sumFibResult").innerHTML = display;
}
}
}
</script>
http://jsfiddle.net/isherwood/38gPs
I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...
Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:
console.log('integer for ' + loopFib + '=' + integer);
Or
console.log('display=' + display);
To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.

compare values in an array to a number in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing a program that determines if a number is between two values in an array.
Here is an example of the array I am using.
var attackArray = new Array (2);
attackArray[0] = new Array("0","1","2","2","2","3","4");
attackArray[1] = new Array("2","3","2","3","2","3","4");
I am using the following code to compare the number against the first two values in the array. I then loop through the array until I find a line that meets the requirements. The number must be >= to the first number and <= the second number.
Here is the code that I am using.
function leveltest ( number)
{
var attack = attackArray.length;
for ( var count = 0 ; count < attack; count ++)
{
if ((number >= Number(attackArray [count][0])) && (number <= Number(attackArray [count][1])))
{
do something ;
}
}
}
If someone can look at my code and explain what I am doing wrong.
I believe you are trying to compare a number to each range of numbers defined by the item values with the same index in element 0 and element 1 of attackArray. If that is right, then the following applies.
The problems present in your code snippet were:
You have the index wrong on line 3. Your third line, attackArray[2] = new Array("1","3","2","3","2","3","4"); is creating a new third element in the attackArray created on the first line. Instead, I think you are wanting to populate the second element of attackArray which should be attackArray[1] = new Array("1","3","2","3","2","3","4"); Or you could use different array syntax as shown below.
In the function, you were using the length of attackArray var attack = attackArray.length;, to control the for loop following. Instead, you will want, var attack = attackArray[0].length; so long as attackArray[0] and attackArray[1] are the same length. You can think of it like this, you were getting your length along the wrong dimension of your array. You were getting the length "down" your array or list of objects, ran than "across" the horizontal dim of your array.
In the function, you are confused on how to loop through the array, and you have this attackArray [count][0] and attackArray [count][1] backwards. Instead they should be attackArray[0][count] and attackArray[1][count]. This will allow you to properly compare your number with each item in element 0 and the item of the same index in element 1.
The following code should be a concise, correct working piece of code to accomplish your goal. You can take and plug this in to jsfiddle.net and it should work in Chrome with the Javascript console used to view the results in the log. Here it is:
var attackArray = [];
attackArray[0] = ["0","0","2","2","2","3","4"];
attackArray[1] = ["1","3","2","3","2","3","4"];
function leveltest (number){
var attack = attackArray[0].length;
for (var count = 0;count < attack;count ++){
if ((number >= Number(attackArray [0][count])) &&
(number <= Number(attackArray [1][count]))) {
console.log(number + " matches at index " + count);
}
}
}
leveltest(2);
Looks like your second element in attackArray has the wrong index.
attackArray[2] = new Array("1","3","2","3","2","3","4");
attackArray.length == 2
you "count" can go up to 1, attackArray[1] is not defined by you.
The second comparation inside the if is wrong. At the second loop it will be attackArray[1][1] and you created an attackArray[0] and attackArray[2].

Filter Number range Function Issue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
SOLVED
From a previous post I did and with the help of some suggestions I have managed to write a function that technically should be doing what I required it to. However the results are not entirely correct.
I have tried to add markup to the JS to explain what is going on, but to explain I have div's like follows:
<div class="section-link">
<div class="price"> £59.99</div>
</div>
<div class="section-link">
<div class="price"> £259.99</div>
</div>
I am trying to have the function hide all these div's and only show the ones if the price is within the given price range.
The data I am passing into the function is: £0.01 - £59.99 or £60.00 - £159.99 or £160.00 - £500.00
from using alert's everything is working fine, however when it gets to the if statement for the filter it is not filtering how it should be.
Any help appreciated
The js:
function price(string){ // passing in the strings as £0.01 - £59.99 and £60.00 - £159.99 etc
$('.section-link').hide(); // hide all section-link div's'
var range = string.replace(/\u00A3/g, ''); // strip pound sign's from range
var rangearray = range.split("-"); // split into 2 value arrays
lowarray = rangearray[0].toString(); // get low value as string
higharray = rangearray[1].toString(); // get high value as string
lowvalue = lowarray.replace(/ /g,''); // strip spaces
highvalue = higharray.replace(/ /g,''); // strip spaces
alert(lowvalue); // testing low value string (is alerting right) - 0.01
alert(highvalue); // testing high value string (is alerting right) - 59.99
$(".price").filter(function(){ //do a filter for all div's with the class of price
var divprice = $(this).text().replace(/\u00A3/g, ''); // strip pound sign from price value
var maindivprice = divprice.replace(/ /g,''); // strip spaces from price value
if (maindivprice >= lowvalue && maindivprice <= highvalue) {
alert(maindivprice); // alerting to see what prices it is saying are between the range (these are showing all the prices and not only ones between the range)
$(this).parent().show(); // show this parents div
} // filter to see if this price is in the price range
});
}
Is it possibly something to do with the decimal points?
Try using parseFloat on your number variable, if this was a string then it is trying to compare a string value to a float value
lowvalue = parseFloat(lowarray.replace(/ /g,'')); // strip spaces
highvalue = parseFloat(higharray.replace(/ /g,'')); // strip spaces
var maindivprice = parseFloat(divprice.replace(/ /g,'')); // strip spaces from price value

Categories