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
Related
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I'm trying to map the maximal amount of days without rain using the TRMM dataset in Google Earth Engine. I'm doing this by iterating over the collection and if no rain has fallen, one gets added to the cell (code below). When rain has fallen the value gets multiplied by 0 so the "counter" is reset. Then I would like to store each result of each iteration in a Image collection and then select the maximum value to get the longest consecutive dry period.
But that is the theory. When I put this in a script I get an error while adding the image of one iteration to a list. Does anyone know why this is and how this can be solved?
Code:
var list = [];
function drylength(current, previous){
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous).multiply(mask);
list.push(sum);
return sum;
}
var dataset = TRMM
.filterDate("2015-01-01","2015-02-01")
.sort('system:time_start:');
var totalPrecipitation = dataset.iterate(drylength, dataset.max()
.remap([0], [0], 0, "precipitation")
.rename('precipitation'));
print(list);
print(totalPrecipitation);
Map.addLayer(ee.Image(totalPrecipitation), imageVisParam);
Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one? Here is an image of the error:
Errors written if image is not visible or for search engines:
Failed to decode JSON.
Error: Field 'value' of object '{"type":"ArgumentRef","value":null}' is missing or null.
Object: {"type":"ArgumentRef","value":null}.
and:
Unknown variable references: [_MAPPING_VAR_0_0, _MAPPING_VAR_0_1].
Something like this to use a multi-value result:
function drylength(current, previous) {
previous = ee.Dictionary(previous)
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous.get('sum')).multiply(mask);
var list = previous.get('list')
list = list.push(sum);
return ee.Dictionary({sum: sum, list: list})
}
...
var totalPrecipitation = dataset.iterate(drylength, {sum: max, list: ee.List([])})
The iterate() function runs on the server, but the list you're attempting to push into is a client-side list; that can't work. If you make it an ee.List, you might be able to get it to work, but you'll have to put it into the previous result (use previous as a dictionary to hold both).
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 7 years ago.
Improve this question
I am creating a game using JavaScript and the canvas API. I would like to implement a score at the top of the canvas which is constructed from a set of sprites on a sprite sheet. I have a sprite sheet containing images of numbers from 0 - 9. I want to know how I would go about displaying the player's current score to the canvas from the set of images. This would be including digits beyond 9(which I think confuses me most). Could you please annotate every line of code here just so I can fully understand.Thank you to everyone who replies.
Here is a quick simple solution using object property names to lookup the image details for each character you want to draw.
Convert the score to a string and then find the character code for each character in the string. Use the character code to look up the image details and then draw the image.
var numbers = { // for each character create a property that has its ASCII code
c48:{
image:imgForZero, // the image for the character zero
offx:0, // x offset if needed
offy:0, // y offset if needed
widthToNext: 10, // distance to the next character so you can have
// variable spacing
},
c49: ... // do the same for each character you want to display
// you can find the codes here
// http://www.w3schools.com/html/html_charset.asp
},
c50: ...
.. and so on
}
var chars = score.toString(); // turn score to a string
var x = 10,y = 20; // the top left of the score position
for(var i = 0; i < chars.length; i++){ // for each character
var charCode = chars.charCodeAt(i); // get the character code
var charData = numbers["c"+charCode]; // get the image details
if(charData !== undefined){ // make sure it is in the data
// draw the image with the offset
ctx.drawImage(charData.image, x + charData.offx, y + charData.offy);
// move to the next character position
x += charData.widthToNext; //
}
}
// All done
I answers to try and stop this getting a negative rating as it is a good question and shows how to use bracket notation to do lookups rather than array.find
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].
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 want return the difference between 2 values how to do that?
0.0.0.1.0 and 0.0.0.1.12
so the difference between these two values is 12
so how to calculate that I tried with Math.abs() but it is fine with single digits.
Assuming that they are strings (since you can't have more than 1 full stop in a valid JS number), you could split it by . character and calculate the difference of individual components:
function numStringDiff(a, b) {
// split them on dot characters
const aParts = a.split('.');
const bParts = b.split('.');
// loop using longest array length as a container for mapped results
return Array(Math.max(aParts.length, bParts.length)).fill(undefined).map((_, i) => {
const i1 = parseInt(aParts[i] || 0); // fetch aParts[i] or default to 0
const i2 = parseInt(bParts[i] || 0); // fetch bParts[i] or default to 0
// return compared value after defaulting the values.
return i2 - i1;
});
}
console.log(numStringDiff('0.0.0.1.0', '0.0.0.1.12'));
The problem here is that, as you stated in the comments, they can be of different length. To make it work in this scenario, we must iterate an amount of times equal to the length of the longest array and ensure that any missing items in the shorter one are defaulted to some non-breaking value like 0 so that we can safely subtract every digit present in the longest list with something or 0.
Note that 0 is a value I only used to ensure you can calculate a difference between different-length arrays, choose any (numeric or float) value that fits your needs.
If in this case the second argument has less dots than the first, negative difference will be returned, otherwise if first is longer than last, positive difference will be returned.
Some examples:
numStringDiff('1.1.1', '1.1') // => [0, 0, -1]
numStringDiff('1.1', '1.1.1') // => [0, 0, 1]
numStringDiff('1.1.1', '1.1.1') // => [0, 0, 0]
For the absolute distance between two values, one can simply .map over this array:
numStringDiff('1.1.1', '1.1').map(num => Math.abs(num));
// OR, using short form:
numStringDiff('1.1.1', '1.1').map(Math.abs);
And finally, should you need the result as a string, simply .join it back together with '.':
numStringDiff('1.1.1', '1.1').map(Math.abs).join('.');
Do know what you are trying to achieve though. If you're trying to manually bisect version numbers (like semver versions) I'd recommend against it since there will always be scenario's uncovered by this function such as pre-releases that wouldn't include only digits but rather 0.0.0-pre-foo-version or something. Since I don't know what it is you're trying to do exactly I'll leave that a responsibility for you to figure out :)