for the loop


I'm trying to code a javascript dice game, using Math.random () to generate die values ​​and a table to hold the current values ​​of each individual die.
The problems I have are 1), the array ends up containing six numbers, and the loop runs only five times, and 2) I can not understand how to get Math.random () to return different numbers on each roll dice.
Here is the function in question:
 var array = [] function rollDice() { for (var i = 0; i <= 4; i++) { var roll = Math.floor(Math.random() * 6) + 1; array[i] = roll; //array.splice(i, 1, roll); } } 
You can see that 'i' iterates from zero to four in the loop (which equals five loops), and on each loop another random number is generated and inserted into the array at the equivalent place.
Regarding the number of elements in the array: if I run the code as shown above, I will get something like this: [1, 2, 3, 4, 5, undefined].
If I run it using the commented line with the 'splice' function (which should remove the value stored at 'i' and replace it with a new value,) I'll get [1, 2, 3, 4 , 5, 6]. How is it if the loop only works five times?
Regarding the difficulty I have in getting the random numbers to change more surely: I tried the following in my loop ...
 var roll; while (roll === hand[i] || roll === null) { roll = Math.floor(Math.random() * 6) + 1; } 

Javascript not producing a random number


I have a while loop to generate a random number that is not the same as any other random number produced before. The random number is used to select a text value of an object.
for example:
 quoteArray[1] = "some text" quoteArray[2] = "some different text" quoteArray[3] = "text again" quoteArray[4] = "completely different text" quoteArray[5] = "ham sandwich" 
This is part of a larger function and after this function has cycled = quoteArray.length it resets itself and starts the cycle again. The problem I have is that the following code is SOMETIMES producing an infinite loop:
 //Note: at this point in the function I have generated a random number once already and stored it in 'randomnumber' //I use this while statement to evaluate 'randomnumber' until the condition of it NOT being a number that has already been used and NOT being the last number is met. while(randomnumber === rotationArray[randomnumber] || randomnumber === lastnumber){ randomnumber = Math.floor(Math.random() * (quoteArray.length)); } 
When I console.log (randomnumber) - when I'm stuck in the loop - I just get '0' accordingly. When it is stuck in the loop, it does not seem that Math.floor (Math.random () * (quoteArray.length)) produces a random number but rather "0" infinitely.
Can anyone tell me why I am facing this problem?
EDIT: Here is the complete complete code with function + variable declarations
  // Function to initialize the quoteObj
      function quoteObj (text, cname, ccompany, url, height) {
              this.text = text;
              this.cname = cname;
              this.ccompany = ccompany;
              this.url = url;
              this.height = height;
          }

  // Fill my Subject quotes with quote information from the XML sheet. 

      var qObj = new quoteObj ('', '', '', ''));
      var quoteArray = new Array ();
      var counter = 0;

  // review each XML element and load the data into an object that is then stored in an array
      $ .ajax ({
          type: "GET",
          url: "quotes.xml",
          dataType: "xml",
          success: function (xml) {
              $ (xml) .find ('quote').  each (function () {
                  quoteArray [counter] = new quoteObj ('', '', '', ''));
                  console.log (quoteArray [counter]);
                  quoteArray [counter] .text = $ (this) .find ('text').  text ();
                  quoteArray [counter] .cname = $ (this) .find ('customer_name').  text ();
                  quoteArray [counter] .ccompany = $ (this) .find ('customer_company').  text ();
                  quoteArray [counter] .url = $ (this) .find ('project').  text ();
                  ++ counter;
              });
          }
      });

  // This is the setion that generates my infinite loop problem.
  // I included all the other code in case people would ask specific questions about how an item was initialized, etc. 

  // Generate a random first citation then progress randomly through the whole set and start all over again.      

      var randomnumber = Math.floor (Math.random () * (quoteArray.length));
      var rotationArray = new array (quoteArray.length);
      var v = 0;
      var lastnumber = -1;

      bHeight = $ ('# rightbox').  height () + 50;
      var cHeight = 0;
      var divtoanim = $ ('# customerquotes').  parent ();

  //NO LINK//
  // Give a height to the inner shadow for the hidden overflow to work with the quotes.
      $ (divtoanim) .css ({'height': bHeight});

  // Rotate the Random Quotations function.
      setInterval (function () {
          randomnumber = Math.floor (Math.random () * (quoteArray.length));

  // check if the function loop should start at the beginning.
          if (v == (quoteArray.length)) {
              rotationArray.length = 0;
              v = 0;
          }
  // determine if the random number is at the same time different from any other random number generated before and it is not the same as the last random number
          while (randomnumber === rotationArray [randomnumber] || random_number === lastnumber) {
              randomnumber = Math.floor (Math.random () * (quoteArray.length));
          }   

          lastnumber = random number;
          rotationArray [randomnumber] = random number;
          ++ v;

  //NO LINK//
  // animation sequence
          $ ('# ctext, #cname').  animate ({'opacity': '0'}, 2000, function () {
              $ ('# ctext').  html (quoteArray [random number] .text);
              $ ('# cname').  html ('-' + quoteArray [random number] .cname);

              cHeight = $ ('# customerquotes').  height () + 50;
              adjustHeight (bHeight, cHeight, divtoanim);

              $ ('# ctext').  delay (500) .animate ({'opacity': '1'}, 500);
              $ ('# cname').  delay (1500) .animate ({'opacity': '1'}, 500);
          });
      }, 15000);

The answer

First of all, since you have updated your question, make sure that you manage the asynchronous data correctly. Because an ajax call is asynchronous, you must make sure that you start the randomizer only after the call is successful and the data returned.
Secondly, assuming you handle the data asyc correctly, the size of your result set is probably too small. So, you probably get the same number at random. Then you can not use this number because you have already done so.
What you need to do is to remove the parts that are already used from the scoreboard each time. Recalculate the length of the array, then draw a random one. However, the probability of this random feeling is very slim.
There is probably a more efficient way to do this, but here is my go:
 var results = ['some text','some text2','some text3','some text4','some text5', /* ...etc */ ], randomable = results; function getRandomOffset( arr ) { var offset, len; if( arr.length < 1 ) return false; else if( arr.length > 1 ) offset = Math.floor(Math.random() * arr.length ); else offset = 0; arr.splice( offset, 1 ); return [ offset, arr ]; } while( res = getRandomOffset( randomable ) ) { // Set the randomable for next time randomable = res[1]; // Do something with your resulting index results[ res[0] ]; } 

Calculate the total of math.random in javascript and return a value

I have three variables that store the random number generated by math.random (), then I have three other variables that store the addition of these three variables, like this:
 var zikT = 0; var hamT = 0; var musT = 0; $("#reset").click(function(){ var random = Math.floor(Math.random() * 12 + 1); var random_0 = Math.floor(Math.random() * 12 + 1); var random_1 = Math.floor(Math.random() * 12 + 1); zikT += (random_0); hamT += (random); musT += (random_1); }) 


My dilemma is that in p the p tag with id leader I want the name of the person who has the largest number that i know i can not explain but i want to do something below:
 if(zikT > hamT && zikT > musT){ $("#leading").html('you'); }else if(hamT > zikT && hamT > musT){ $("#leading").html('me'); } else if(musT > zikT && musT > hamT){ $("#leading").html('i'); } 

Math.random and splice to randomly remove array elements


I read Deleting the table elements in JavaScript - delete vs splice (among other things) that helped, but I still do not know why the code below works as it does.
There are 10 divs with the class "names" on the page. All currently with an opacity of 1 (included for context).
I try to randomly choose 5 of them, and change their background color to "red". After using splice () I would expect the array size to decrease by 1 but that does not happen.
See the live example here: http://jsfiddle.net/RussellEveleigh/Fr85B/1/
 var z = document.getElementById("selected"); var r = function () { b = document.getElementsByClassName("names"); c = []; d = []; for (i = 0; i < b.length; i++) { if (window.getComputedStyle(b[i]).opacity == 1) { c.push(b[i]); } } for (i = 0; i < 5; i++) { num = Math.floor(Math.random() * c.length); z.innerHTML += c.length; // would expect "109876" d.push(c[num]); c.splice(num, num); } for (i = 0; i < d.length; i++) { d[i].style.backgroundColor = "red"; } }; r(); 

Deleting array elements in JavaScript - delete vs splice

What is the difference between using the delete operator on the array element and using the Array.splice method?
For example:
 myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // or myArray.splice (1, 1); 
Why even have the splice method if I can delete array elements as I can with objects?

The answer

These are different things that have different purposes.
splice is table-specific and, when used for deletion, removes table entries and moves all previous entries to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it is not a non-op call: theArray.splice(x, 0) ) .
delete is not table-specific; it is designed to be used on objects: it deletes a property (key-value pair) of the object on which you use it. It only applies to arrays because standard arrays (for example, untyped) in JavaScript are not really arrays *, they are objects with special processing for some properties, such as those whose names are " indexes of arrays "defined as string names" ... whose numerical value is between +0 ≤ i < 2^32-1 ") and the length . When you use delete to delete an array entry, all it does is delete the entry; it does not move subsequent entries to fill the vacuum, so the array becomes "sparse" (some entries are missing). It has no effect on the length.
Some of the current answers to this question incorrectly indicate that using delete "sets the entry to undefined ". It's not correct. It removes the entry (property) entirely, leaving a void.
Let's use code to illustrate the differences:
 console.log("Using `splice`:"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 a.splice(0, 1); console.log(a.length); // 4 console.log(a[0]); // "b" 
 console.log("Using `delete`"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 delete a[0]; console.log(a.length); // still 5 console.log(a[0]); // undefined console.log("0" in a); // false console.log(a.hasOwnProperty(0)); // false 
 console.log("Setting to `undefined`"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 a[0] = undefined; console.log(a.length); // still 5 console.log(a[0]); // undefined console.log("0" in a); // true console.log(a.hasOwnProperty(0)); // true 

Minimal jQuery Alert and Confirm Replacements


I recently made the decision to stop using modal dialogs in my apps. What once was a good way to obtain information or confirmation has become undesirable and taboo in the world of UX.
However, sometimes a simple window.alert() or window.confirm() is necessary, particularly to confirm some kind of irreversible operation. But the default system alert and confirm methods block script execution and aren't very pretty.
So here's a 150 line jQuery plugin that provides a minimal yet highly customizable replacement for window.alert() and window.confirm().

Features

  • Simple syntax.
  • Minimal default styles; easy to customize or write your own.
  • Show/hide hooks for adding custom animation (works well with Velocity.js).
  • Prevents focus from leaving the modal.
  • Returns promise-compatible (jQuery deferred) for ok/cancel actions.
  • Compact! (about 150 lines)
Best of all, you can easily customize them to match your app perfectly. And the show/hide hooks play nice with $.animate$.velocity, or whatever animation library you prefer to use.

Example


  • // Alert

  • $.alertable.alert('Howdy!');


  • // Confirmation

  • $.alertable.confirm('You sure?').then(function() {

  • // They clicked ok!

  • });


Demo

Installing with NPM

npm install --save @claviska/jquery-alertable

Docs / Downloading / Contributing

You can read the docs, download the latest source or contribute to this project on GitHub. Please submit bugs to the issue tracker and implementations questions to StackOverflow. 
This plugin is licensed under the MIT license.

This looks familiar

Many years ago I wrote a similar plugin like this, but it was more bloated and came with some crazy 2000-ish styles. That version has been archived for a few years now, but you can find it here for historical reference.

Rewriting JavaScript: Sum an Array


A series covering how to rewrite common snippets of Javascript using function concepts. In this post we are going to cover how to find the sum of an array.
First, we will cover the standard method that you’ll recognize clearly. Even if you’re not a Javascript developer this example should ring a few bells.

The Standard Way

var numbers = [10, 20, 30, 40] // sums to 100
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i]
}
In The Standard Way we first declare the variable sum and set its initial value of zero. Next, we use a standard for loop to iterate through our array numbers and total up the array using sum. Simple, but not really the best solution.
One of the biggest problems with this snippet of code is that we introduce mutation into our code. In short, we created the variable sum whose value is changed at a later point. This is bad for readability as well as being more error prone than code which avoids mutation.

The Rewritten Way

Luckily Javascript provides us with ways to write immutable code, which I will demonstrate below. Changes are marked in bold.
const numbers = [10, 20, 30, 40] // sums to 100
// function for adding two numbers. Easy!
const add = (a, b) =>
a + b
The first thing to note is that we changed numbers from a var to a const . We want to make sure that numbers is a constant; it’s not going to change. For more on const and let, see this fantastic article by Mozilla.
Next, you will notice that we added a function called add. This function simply takes two numbers and adds them together. If you have not seen this syntax before I recommend checking out this MDN page on Arrow Functions.
Next, we will write the segment that adds our array.
const numbers = [10, 20, 30, 40] // sums to 100
// function for adding two numbers. Easy!
const add = (a, b) =>
a + b
// use reduce to sum our array
const sum = numbers.reduce(add)
One line, and we’re done. Working from left to right notice that we set the variable sum as a constant. Once this variable is set we do not want it changing as that would introduce mutation.
Next, you will notice that we execute the method reduce on numbers, and set it to the variable sum eliminating the need for mutation. The reduce method accepts a function that takes 4 arguments. In our case, we only need the first two. The first two arguments are as follows.
  1. accumulator — The value returned from the last callback.
  2. currentValue — The current element being processed in the array.
Because we give reduce the function add, the values accumulator and currentValue get mapped to a and b in our add function respectively.
For more clarity of what is happening, let’s break it down step by step for each value in our array as it is processed by the reduce statement.
First Iteration: In the first iteration of the array the values are as follows: accumulator = 10 and currentValue = 20 added together we return 30.
Second Iteration: In the second iteration of the array the values are as follows: accumulator = 30 and currentValue = 30 added together we return 60.
Third Iteration: In the third iteration of the array the values are as follow: accumulator = 60 and currentValue = 40 added together we return 100.
As you can see in each of this iterations, the accumulator is the value returned by each execution. Once you break it down, the reduce method becomes quite simple to understand. Check out the MDN article on reducers for more info. I highly suggest you read it carefully to understand what else reduce has to offer.

The Wrap

By replacing the standard loop with reduce, we have removed the mutation from our code, allowing for cleaner, easier to read code that will benefit us as our application grows.
I’ll be covering more topics in the near future about rewriting basic Javascript concepts using the new standards. Until then I suggest you take a look at the useful readings below for more info on the above topics.

JavaScript Variable


One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
  • Numbers, eg. 123, 120.50 etc.
  • Strings of text e.g. "This text string" etc.
  • Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money
= 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
  • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document
.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.
  • You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
  • JavaScript variable names are case-sensitive. For example, Name and name are two different variables.

JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
abstractelseinstanceofswitch
booleanenumintsynchronized
breakexportinterfacethis
byteextendslongthrow
casefalsenativethrows
catchfinalnewtransient
charfinallynulltrue
classfloatpackagetry
constforprivatetypeof
continuefunctionprotectedvar
debuggergotopublicvoid
defaultifreturnvolatile
deleteimplementsshortwhile
doimportstaticwith
doubleinsuper