i was coding for a small project but my random array picker doesnt work
var btnarray = [xfn.left, xn.left, xnln.left, xln.left, xnn.left];
(this is the array)
var rand = btnarray[Math.floor(Math.random() * 4)];
(this is the random picker var)
Well, when i start, the rand value results equal to btnarray[0]
anyone can help me please?
Oh i perfectly know that the variables are all different.
Thanks
Since your array's length is 5, you need to multiply the value of the random function by that number. Better yet, use the length property.
var rand = btnarray[Math.floor(Math.random() * btnarray.length)];
You shouldn't use Math.floor since it will make very hard to get the last element in your btnarray array, you'll need to get exactly the number btnarray.length in order to get at that element. Also, floor tends to flatten probability outcomes and looks like you're stuck on some value(s) since it's threshold is forcing you to have the greatest integer smaller than or equal to some number.
You should use round instead, this will even the probability for every array element and will give you more apparently random indexes. Try this, it's already tested with a dummy btnarray array variable and works fine.
var rand = btnarray[Math.round(Math.random() * btnarray.length)];
if you toss this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
you can just do this:
var randomValue = rando(btnarray).value
I usually go with randojs.com because it can handle pretty much any random functionality you need, and it's all short and easy to read.
Related
My code in Javascript involves manipulating several variables and displaying a few of them in counters on-screen. Because of the math I'm using, I'll end up with numbers such as 1842.47167... or something similar. I want to display the number as 1,843 (rounded and with the "thousands" comma added). Does anyone have a simple and easy way to do it? See below for code I've tried.
console.log(coins) //Output: 1842.4716796875
commaCoins = coins;
commaCoins = Math.round(coins);
commaCoins = coins.toLocaleString();
console.log(commaCoins) //Output: "1,842.472"
//Desired result: 1,843
Anyone have a better way to do this?
You'll need to work with strings to achieve that.
Something like:
const coins = 1842.4716796875;
const roundedCoins = Math.round(coins);
const dotFormat = roundedCoins / 1000
const commaFormat = dotFormat.toString().replace('.', ',');
console.log(commaFormat) // Output: 1,842
You can obviously do that in less step and use Math.ceil() if you need to round to the upper unit.
OS: CentOS7
I run "OpenWebSpider v0.3.0" on my local server (for searching/indexing). ~its working as it should. when i receive the "results", it shows "Relevancy XX.XXXXXXXXXXXXXX".I would like to shorten that to only 3 Decimal places; "XX.XXX"..
enter image description here
I am new here, and to some of this javascript. i think i have found what i need to embed? The toFixed()Method, but i cannot determine where exactly, or for that matter If that is the best way to accomplish this seemingly simple task.?:)
this is (what i am thinking) is the relevant "code" area.
enter image description here
Being a newbie at this i have tried various areas to edit or just add this: for (var i = 0; i.toFixed(2); i < results.length; i++)
to the "code area" that is pictured above (pic 2); (with a lot of variations) all results are none though. so far.
Sorry if my "Question" is Not compliant, i will work on it, i absolutely have the highest respect for stackoverflow, and what it is.. Thank you very much.
Well if you just want to print out the number with reduced decimals toFixed() wil do fine. But notice that it will change your number to a string. One other way to do it would be to use Math.round (). In your case to get 3 decimals it would be
Math.round(your_number * 1000) / 1000.
And for your loop. for (var i = 0, i.toFixed(2); i < results.length; i++) (assuming the first ; should be a ,) won't work because i.toFixed(2) will not only get executed once at the beginning of your loop, it also gets applied to i which is just your loop-counter. You need to apply it like this inside your loop:
results[i]['relevancy'].toFixed(3).
All I'm trying to do is display the math.random number in the h1 tag by using jQuery and for some reason it's not working I'm not sure whats going wrong. For some reason when I take out the function it works but why is that?
HTML
<h1></h1>
jQuery
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
You are using $ which is a jquery selector in a form that doesnot know about JQuery .
So please use this code instead :
function Thetime(){
$(document).ready(function() {
var number = Math.floor(Math.random());
$('h1').text(number);
});
}
Hope this will solve your problem .
a side note : you are flooring the generated number , that might always lead to ZERO , So you can also only use Math.random() instead of Math.floor(Math.random());
Thanks
You need to actually call the time() function to make it perform its operations.
Here is your code running:
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
// call your function to run it
time();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
NOTE: You may notice that your number is always 0. This is because Math.random() creates a float between 0 and 1 (eg: 0.22378). Likewise, Math.floor() will take any floating point number and round it down to the nearest integer. So a random number like 0.22378 will always be floored to 0. If you want to randomize between a range of whole numbers you need to multiply your random number by your maximum then floor the result.
var max = 30;
var number = Math.floor(Math.random() * max);
#ScottMarcus answered the question, all I had to do was add a document.ready to the function. Just going to leave this up for any new beginning coders.
Allo'
I'm working on a little project of mine and part of it involves taking a two dimensional array already created and randomizing it.
So I have something which looks like this:
foo = [[1,2],[3,4],[5,6],[7,8]];
randomizeFoo = function(){
var randomizedFoo = [];
newFoo = foo;
for(i = 0; i < newFoo.length; i++){
count = Math.random() * newFoo.length;
randomizedFoo.push(newFoo.slice(count, count + 1));
}
return randomizedFoo;
};
This does indeed randomize the array but I end up with something like this:
randomizedFoo = [[[7,8]],[[1,2]],[[5,6]],[[3,4]]]
My nice neat 2D array is now a 3D array with the lowest level arrays now burred under an extra level. I realize that this is not really that big a deal and the rest of my code just needs to compensate but it bugs me for 2 reasons:
It's extra complexity and that's never good.
I don't like my code doing things without me knowing the reason why.
Anybody have any ideas as to why it's doing this? I put a 2D array in, I want a 2D array back out again.
It's because you are using slice. Just use count as the index into foo. As in : randomizedFoo.push(foo[count]);
Make sure you make count an int first.
You can take the script from this answer and use map with it:
foo = range(0, foo.length-1, true).map(function(i) {
return foo[i];
});
Demo: http://jsbin.com/ayepeh/1/edit (ctrl + enter to refresh)
I am trying to divide two variables in Jquery as follows:
var image_width = parseInt($object.width());
var image_height = parseInt($object.height());
var image_ratio = image_width/image_height;
However, when I attempt to use image_ratio in an if statement...
if (image_ratio < 1) //image is taller than it is wide
{
//do something...
}
And I know that the image is taller than it is wide but the function is not entering the if statement. Is this because when two int's divide it generates an int? If so, how can I get decimal values in order to check if the ratio is less than 1?
Thanks!
what is the result of alert($object.height())? If it's possible that $object is an empty jquery collection, then.height() will return null, and parseInt(null) will return NaN, giving you NaN for image_ratio. Any comparison between NaN and another value will always return false, which would explain the behavior you're seeing.
if $object.height() is returning 0, you'll also get NaN for image_ratio, and then you need to look at your jQuery selection. Are you selecting the correct element? What does $object[0].height give you?
JavaScript doesn't have ints, only "Numbers" (double-precision floating point), so that's not the problem.
Check the actual values of each variable.
You have something else wrong because dividing two numbers will return a decimal value if they don't divide perfectly evenly. Here's a jsFiddle to see for yourself: http://jsfiddle.net/jfriend00/wnh9Q/.
var width = 4;
var height = 3;
var aspectRatio = height/width;
if (aspectRatio < 1) {
$("#if").html("Inside the if() statement."); // it goes in here
}
$("#result").html(aspectRatio); // outputs 0.75
To solve your issue, you need to look at the input values $object.width() and $object.height() and see what is wrong there.
At which point are you calling the width() and height() functions on the image object? If the image isn't yet loaded when the values are retreived, the values are probably wrong. In this case, try calculating the ratio in a function attached to the load event on the image.
No, the division doesn't give an integer result. The parseInt method doesn't give an integer result either, because there is no integer data type in Javascript.
Besides, the width and height methods returns numbers, not strings, so there is no point to parse them. That would only convert the number into a string, and then back to a number. Just get the values:
var image_width = $object.width();
var image_height = $object.height();
There is however nothing in your code that would not work, so there has to be something outside the code that you show that doesn't work.
Some possible reasons:
$object doesn't contain any elements.
The image is not loaded yet, so the element doesn't have any size.
If it's the latter, you should run your code in the load event rather than in the ready event.