Getting NaN error as the result - javascript

I seem to be getting a NaN error as the result in my JavaScript code.
I'm pretty new to this, would appreciate any help.
Solved by giving value to the total var.

There are a couple of problems:
You should use parseFloat instead of using strings.
You should initialize total (this is what causes the nan)
You should initialize arrays properly.
function tax() {
var price = new Array(10);
var quant = new Array(10);
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = parseFloat(prompt("Insert Quantity: "));
price[i] = parseFloat(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}

I guess with this var price = [10] you were trying to create an array with 10 numbers, but that is not the way it works in Javascript var price = [10] will give you an array with 10 at the 0th position. The only other tweak I would make there is make var price = [1,2,3,4,5,6,7,8,9,10] to actually achieve what you set out for initally

First of all, JavaScript is not Java ;)
You seem to try to initialize your arrays with a length of 10. This works in Java but in Javascript an array is dynamic and writing :
myArray = [10];
will just set the value 10 in the first index of the array.
Then, as you prompt the user to input numbers, the numbers will be interpreted as a string.
So it would be good to cast it to a number before working with it.
To cast it :
var value = '10000';
valueAsInt = parseFloat('10000',10);
//or simply
valueAsInt = +value;
Now we come to your problem, as total is not initialised, the first affectation will be
undefined += n;
this will give a NaN.
So just initialise total before using it :
var total = 0;

you have to initialize total variable first because it is undefined initially
var total = 0;

You have to parse the String variables to a Number:
function tax() {
var price = [10];
var quant = [10];
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = Number(prompt("Insert Quantity: "));
price[i] = Number(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}
tax()

Related

How do read the last character per string?

My code generates a string, as shown in the image. At the end of each line a number in euros is shown, let call these euros1 and euros2. The idea is that the amount ✓ icons is multiplied with euros1 and euros2 shown per line. So in the case of my example: (10,45 + 5,50) x 2 = 31,90 for the first line, and for the second line (18,24 + 9,60) x 3 = 83,52. These numbers are supposed to be combined to a total of 115,42.
However my current code produces a total of 218,95. So it takes the sum of all the euros1 and euros2 and multiplies it by the total amount of ✓ icons.
How can I calculate the sum of the euros1 + euros2 x the amount ✓ icons, per line?
I think a for loop could help me, however I am new to Javascript and I am not sure how to proceed.
var temp = g_form.getValue('mwadm_onkosten_list_refList_changes');
var count = (temp.match(/✓/g) || []).length;
var lastChar = temp[temp.length -1];
if (count != temp);
{
total = total * count;
}
I was thinking of a split solution just like #dganenco mentioned. I created a TEMP variable to reproduce your result string. And execute a function on it foreach row.
And i intentionally kept it really simple. Hope this helps.
var temp = ["✓|| €10,45 | €1,50 ", "✓|| €10,45 | €2,50 ", "✓|| €10,45 | €3,50 "];
var totalTimes = (String(temp).match(/✓/g) || []).length;
//perform function for each row
temp.forEach(CalculateRow);
//Splits the row, Gets euro1 as decimal, euro2 as decimal, calculates the amount a character is found, calculates total, prints it to console.
function CalculateRow(item, index) {
var arr = item.split('|');
var euro1 = GetValueFromArray(arr,1);
var euro2 = GetValueFromArray(arr, 2);
var times = (String(arr).match(/✓/g) || []).length;
var _total = (euro1 + euro2) * times;
console.log(_total);
}
//Takes the index value, and casts it to decimal value
function GetValueFromArray(arr, index){
var getindex = arr.length -index;
var result = arr[getindex];
result = result.replace('€', '');
return parseFloat(result, 10);
}
I've got a solution for you in case if is it possible to only split strings by | symbol, then get last 2 values and do all needed stuff using them.
const strArr = ['asd|addf|$56.60|$10.40', 'asd|addf|$5.60|$1.40'];
let sum = 0;
strArr.forEach(str => {
const splitted = str.split('|');
debugger;
const x = getNumber(splitted[splitted.length - 2]);
const y = getNumber(splitted[splitted.length - 1]);
sum += (x+y)*2;
});
function getNumber(str){
return +str.substring(1);
}
console.log(sum)
Assuming temp is the multiline string in the form of
asd|√|√| €12.34 | €15.25
zxc|√|| €18.34 | €19.25
This code should give you a sum of last two numbers multiplied by the amount of √
var temp = "asd|√|√| €12.34 | €15.25\nzxc|√|| €18.34 | €19.25"
let lines = temp.split('\n')
let linesSummaries = []
for(let line of lines){
var count = line.match(/√/g).length
var vars = line.split('|')
var x = parseFloat(vars[vars.length-1].match(/\d+\.?\d*/))
var y = parseFloat(vars[vars.length-2].match(/\d+\.?\d*/))
var lineSum = (x + y ) * count
linesSummaries.push(lineSum)
}
console.log(linesSummaries)

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

How do I take a variables prior value and subtract it from the final value if the total value of the variable cannot exceed a certain amount?

example:
var num = 20;
var sub = 6;
var add = 10;
num = num - sub;
num = num + add;
if (num>20){
num = 20;}
console.log("X was added to var num");
How can I get the console log to say that var num really only had 6 added to it before it hit it's max value?
Your question isn't very clear. Do you need to keep a log of what num is?
I would reccomend an array for that:
let log = [];
Then before you change num:
log.push(num);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If you just want the console to display the value of a variable there's several ways:
console.log(add, " was added to var num");
console.log(add + " was added to var num");
console.log(`${add} X was added to var num`);
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Push command in Javascript won't create the correct multidimensional array

I'm attempting to generate 10 random numbers 3 times and capture the hi, the lo, and last in every 10 number batch. I create an array of the hi/lo/last that gets pushed into another array so I can keep track of the numbers. Unfortunately the push command below seems to be only adding the last hi/lo/last 3 times, instead of each hi/lo/last. Not sure what I'm doing wrong.
Also, I clearly am not an expert programmer having worked mostly with VBA in excel where I could step through a program. Is there any way to do that in Sublime with Javascript? I'm working in a windows environment, using Sublime Text 2, with a Node build for Javascript.
Thanks in advance for the help.
var price;
var hiPrice;
var loPrice;
var intervalPrices = []
var initialPrices = [];
var rows = 3;
var columns = 3;
var randomPrices = function(){
price = 1
hiPrice = price
loPrice = price
for (var i = 1; i <= 30; i++){
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000
priceIs()
if (i%10 == 0){
intervalPrices[0] = hiPrice
intervalPrices[1] = loPrice
intervalPrices[2] = price
initialPrices.push(intervalPrices)
hiPrice = price
loPrice = price
}
}
}
var priceIs = function(){
if (price >= hiPrice) {
hiPrice = price
}
if (price < loPrice) {
loPrice = price
}
}
randomPrices()
console.log(initialPrices)
Try making separate object or make it clone instead of original object.
initialPrices.push([intervalPrices[0], intervalPrices[1], intervalPrices[2]])
Now
console.log(JSON.stringify(initialPrices))
[[1.00092,0.99835,0.99906],[0.99906,0.99758,0.99762],[0.99907,0.99734,0.99907]]
Its just a prob of variable reference whenever you edit intervalPrices it will override prev value of intervalPrices. Pushing same variable with different value will not preserve the value already pushed to the array as every element of that array points to the same intervalPrices variable.
your updated code - read comment for better understanding
var randomPrices = function(){
price = 1
hiPrice = price
loPrice = price
for (var i = 1; i <= 30; i++){
//create a new Object
var obj = {};
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000
priceIs()
if (i%10 == 0){
//assing new values to the Object
obj[0] = hiPrice
obj[1] = loPrice
obj[2] = price
initialPrices.push(obj)
hiPrice = price
loPrice = price
}
}
}
Using the same variable name to build the array you're trying to push is causing you your issues. Try this instead:
for (var i = 1; i <= 30; i++) {
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000;
priceIs();
if (i%10 == 0){
initialPrices.push([hiPrice,loPrice,price]);
hiPrice = 1;
loPrice = 1;
}
}
I also set hiPrice and loPrice back to 1 rather than the random number that was generated.

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

Categories

Resources