Hello
I’m currently having problems with a personal project. Here is my current JS
$(document).ready(function() {
console.log('Bonnets');
$('#field').focus();
$('#field').keypress(function(e) {
var key = (event.keyCode ? event.keyCode : event.which);
var numbersReactants = [];
var numbersProducts = [];
if (key == "13") {
//Upon enter sign, do an equals check
var input = $('#field').val();
if(input.indexOf('=') >= 0) {
console.log(input);
var reactants = input.split('=')[0];
var products = input.split('=')[1];
//Starts reactants check
if (reactants.indexOf("+") > 0) {
reactants = reactants.split("+");
} else {
reactants = [reactants];
}
for(var i = 0; i<reactants.length; i++) {
reactants[i] = reactants[i].replace(/\s/g,'');
if (isNaN(reactants[i][0])) {
reactants[i] = "1" + reactants[i];
}
}
// Gets numbers
for (var i = 0; i<reactants.length; i++) {
$.getJSON("https://enthalpy-api.herokuapp.com/" + reactants[i] + '/', function(result) {
numbersReactants.push(result);
});
}
//Starts products check
if (products.indexOf("+") > 0) {
products = products.split("+");
} else {
products = [products];
}
for(var i = 0; i<products.length; i++) {
products[i] = products[i].replace(/\s/g,'');
if (isNaN(products[i][0])) {
products[i] = "1" + products[i];
}
}
//Gets products numbers
for (var i = 0; i<products.length; i++) {
$.getJSON("https://enthalpy-api.herokuapp.com/" + products[i] + '/', function(result) {
numbersProducts.push(result);
});
}
//Final Sum
var productSum = 0;
for (var i = 0; i<numbersProducts.length; i++) {
productSum += Number(numbersProducts[i][1]);
}
var reactantSum = 0;
for (var i = 0; i<numbersReactants.length; i++) {
reactantSum += Number(numbersProducts[i][1]);
}
console.log(numbersReactants);
console.log(numbersProducts);
console.log("Final Enthalpy: ", (productSum - reactantSum));
}
}
});
});
If you look towards the end of the project, the last few lines logs the variables numbersProducts
and numbersReactants
. The two variables log both fine. See below for a screenshot of the numbersProducts
variable under the sample equation N2(g) + 3H2(g) = 2NH3(g)
. As you can see, it logs just fine, however, if I try to log numbersProducts[0]
or anything added onto that, it pulls an error.
Do you have any ideas on how I can fix my problem?