This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to simplify this code?
What is the best way to simplify this for going from 1-19?
var backer1 = document.getElementById("backer-prediction-1").value;
var incentive1 = document.getElementById("incentive-cost-1").value;
var totalIncentive1 = parseInt(backer1,10) * parseInt(incentive1,10);
document.getElementById("incentive-total-1").value = totalIncentive1;
var backer2 = document.getElementById("backer-prediction-2").value;
var incentive2 = document.getElementById("incentive-cost-2").value;
var totalIncentive2 = parseInt(backer2,10) * parseInt(incentive2,10);
document.getElementById("incentive-total-2").value = totalIncentive2;
Last one I posted they gave me a "for" loop.
Still learning this stuff.. Very New, THANKS!!!
Just like the last question, use a for loop:
for(var i = 1; i < 20; i++){
var backer = document.getElementById("backer-prediction-"+i).value;
var incentive = document.getElementById("incentive-cost-"+i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-"+i).value = totalIncentive;
}
for (var i=1; i<=19; i++) {
var backer = document.getElementById("backer-prediction-" + i).value;
var incentive = document.getElementById("incentive-cost-" + i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-" + i).value = totalIncentive;
}
This untested code should be enough, unless you need access to the backer and incentive values for each one of the cases after the loop is completed.
Use Array in javascript
var backer=[],
incentive=[],
totalincentive=[];
for(var i=1;i<20;i++){
backer[i] = document.getElementById("backer-prediction-"+i).value;
incentive[i] = document.getElementById("incentive-cost-"+i).value;
totalIncentive[i] = parseInt(backer[i],10) * parseInt(incentive[1],10);
document.getElementById("incentive-total-"+i).value = totalIncentive[i];
}
So you can use them after ending for loop , like
backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]
If the value of backer and incentive is a number, I'd be tempted to do:
var get = document.getElementById;
var backer, incentive, totalIncentive = 0;
for(var i = 1; i < 20; i++) {
totalIncentive += get("backer-prediction-" + i).value * get("incentive-cost-" + i).value;
}
as the multiplication will implicitly convert numeric strings to numbers. But you really should validate that the content of those elements is a valid number before doing anything, even if using parseInt.
Related
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I have made a piece of code that generates a random code of 12 characters. I am using Math.random and for-loops to do this. On the page you can write in an input how many codes you want.
What I want to do is save the generated codes in an array, however I can't do this because the for-loop and Math.random creates the code number by number and places them after each other. How can I add the whole 12 digit code to my array (so I can use it later)?
I've tried array.push with no luck. What works is outputting the numbers to DOM object in HTML, like this:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
But that doesn't put the 12 digit code into a variable. I've also tried this:
var codeNumber = "";
codeNumber += mathRandom;
But that ends up in the variable value having only 1 digit.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
I expect the codes created (after some changes) to be added to the array, so that I can later use the codes on the page. Each individual 12-digit code needs to have its own place in the array.
This should work:
var result = [], stringResult;
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
result.push(mathRandom);
}
stringResult = result.join(''); // concatenates all the elements
console.log(stringResult);
The problem with your code is that + sign attempts to determine types of the operands and to choose the right operation, concatenation or addition. When adding stuff to innerHtml it treats the number as string. That is why it worked.
You'll want to refactor things so generating a single code is encapsulated in a single function (generate() here), then use that function's output, like this. (I hope the comments are enlightening enough.)
var numberOfCodes = document.querySelector("#numberOfCodes");
var resultDiv = document.querySelector("#result");
function codeGen() {
var nToGenerate = parseInt(numberOfCodes.value);
for (var a = 0; a < nToGenerate; a++) {
var code = generate(); // generate a code
// you could put the code in an array here!
// for the time being, let's just put it in a new <div>
var el = document.createElement("div");
el.innerHTML = code;
resultDiv.appendChild(el);
}
}
function generate() {
var code = ""; // define a local variable to hold the code
for (i = 0; i < 12; i++) { // loop 12 times...
code += Math.floor(Math.random() * 9); // append the digit...
}
return code; // and return the value of the local variable
}
<input type="number" id="numberOfCodes" value=8>
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
As this answer shows, this should work for you:
function makeRandCode() {
var code = "";
var ints = "1234567890";
for (var i = 0; i < 12; i++) {
code += ints.charAt(Math.floor(Math.random() * ints.length));
}
return code;
}
console.log(makeRandCode());
The problem is that you are adding numbers and what you really want is to concatenate them, the solution is to transform those numbers into String, then save them in the variable where you want to store them. An example:
2 + 2 = 4 and '2'+'2'='22'
Just use .toString() before save it in to the variable.
I didn't find an answer to this, I need to concatenate two variables (ans & i) in Jquery to get ans1, ans2, etc. I tried this:
if(preguntaTipo<2){
var numero = "";
}
else{
var numero = $('#numero').val();
for (var i = 1; i < numero; i++) {
var ans.i = $('#ans'+i).val();
}
}
Its a mode to do like PHP $ans.$i? I also tried ans + i and it didn't work...
var ans.i = makes no sense.
You can't have periods/dots inside of variable names.
Is this what you're looking for?
var ans = [];
for (var i = 1; i < numero; i++) {
ans[i] = $('#ans' + i).val();
}
You could also use ans.push($('#ans' + i).val()); which would make the resulting answer array 0-based instead of 1-based.
Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.
I would like to know if there is a way of creating a JavaScript object which is randomized. Understand randomized as such: the resulting object has a random set of properties, every of which has a random name. The problem boils down to two:
1) Is it possible to have an object created at runtime, without earlier specifying the amount of properties?
2) Is it possible to randomize names of the object's properties?
I'm looking for an explanation/solution, not only a no/yes answer.
A very crude way to do it, can't think of any use case for it:
function randomObject(){
var ret = {};
var propertyCount= Math.random() * 10;
for (var x = 0; x < propertyCount; x++ ){
ret[Math.random()] = Math.random();
}
return ret;
}
I don't see how it could be useful, but yes, it's possible.
var MAX_PROPERTIES = 50;
var ALLOWED_CHARACTERS_IN_KEY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
var MAX_KEY_LENGTH = 30;
var object = {};
var propertiesCount = Math.round(Math.random() * MAX_PROPERTIES);
for(var i = 0 ; i < propertiesCount ; i++) {
var keyLength = Math.round(Math.random() * MAX_KEY_LENGTH);
var randKey = "";
for(var j = 0 ; j < keyLength ; j++) {
randKey += ALLOWED_CHARACTERS_IN_KEY[Math.floor(Math.random() * ALLOWED_CHARACTERS_IN_KEY.length)];
}
var randValue = Math.random();
object[randKey] = randValue;
}
Note that some keys could begin with a number, which is not callable with the dot notation.
Example :
{
"NmkQZWeW9_ojadERwK74HXYj43Lw":0.3039316821878978,
"PZiFauEC6H":0.04273172815465165,
"2m7cMrwRPoxpa8LvmpAaJ":0.7010494474513925,
"D":0.4552683870622114,
"HQhIxPxO8tsdocRuGJpnhB7k2PjD":0.18360190519964337,
"rVwM8":0.8681098855694265,
"3Vf5HGYDOmUli3":0.527829742115212,
"fQ4ryGL2cxhJeRd":0.10353706566292953,
"D_DQqODu_":0.1272988336424956,
"8UY0a7":0.17057184875868092,
"8i1uVtPwzl0KRA8iYZ4uKcPKF":0.9554370948377217,
"TTi":0.038665872114993616,
"YofUj9RrK7foQrl":0.5835241172217945,
"sb3SzEB_":0.17136910050721899,
"801FopHCCML4ozrfmjak":0.10999126507324442,
"D8":0.05981337403919851,
"oL8ZZvrAG":0.36816486041399255,
"hfXxJ0sNp42y2HYEDXLBYgZ6mV":0.13977757384990708,
"2xx4AJrQswA5TIcXr":0.8610074761855161,
"68RNcKQmgnh_qTG":0.5234909406332302,
"wJsV8BRo1cT2MtXDuh":0.4497261910215308,
"6yFr4E81bvXK":0.5996413679577888,
"Px2bjBvFSBu":0.017922504534248707,
"yazK1KQbmUhE4Ul1rZX5hf0yulX_JK":0.7105144243046027,
"cXmdnvmP":0.028121925940253756,
"R_fDjw9yBejk3":0.699514797889162,
"z":0.34347612922580006,
"2kTX6Q2tzbCo3":0.678962211994213
}
I have a problem with my code.
$('input[name="pocet"]').each(function(){
var $mnozstvo = parseInt($('this').val());
var $id = parseInt($(this).attr('id').substring(6));
var $aktualnyProdukt = $('#' + $id);
var $povodnaCena = parseFloat($aktualnyProdukt.data('price'));
var $riadkoveZlavy = $aktualnyProdukt.find('div .vypocetPreZlavu');
var $aktualnaCena = $povodnaCena;
if($riadkoveZlavy.length > 0) {
$riadkoveZlavy.each(function() {
$mnozstvoNaZlavu = parseInt($(this).data('mnozstvo'));
$cenaPoZlave = parseFloat($(this).data('cena'));
if($mnozstvo >= $mnozstvoNaZlavu) {
$aktualnaCena = $cenaPoZlave;
}
});
}
if(isNaN($mnozstvo)) $mnozstvo = 0;
total += $mnozstvo * $aktualnaCena;
});
However, after running this function, total returns NaN and I have no idea why. Could you help me?
HTML:
http://jsfiddle.net/UL7Sr/
var $mnozstvo = parseInt($('this').val()); should actually be var $mnozstvo = parseInt($(this).val());
Additionally, make sure that $aktualnaCena is a number. You do this for $mnozstvo, but not for $aktualnaCena. Try:
if(isNaN($mnozstvo)) $mnozstvo = 0;
if(isNaN($aktualnaCena)) $aktualnaCena = 0;
total += $mnozstvo * $aktualnaCena;
Also, please don't prefix all your variables with a $. JavaScript is not PHP. The convention when using jQuery is that you do that for jQuery element variables to distinguish from other variables. If you use it for all your variables in that context, it is actually confusing.
var $povodnaCena = parseFloat($aktualnyProdukt.data('price'));
var $povodnaCena = parseFloat($aktualnyProdukt.attr('data-price'));
Replacing the first line with the second one solved my problem.