Why displays NAN?

var x= document.getElementById('i1').value;
var y= document.getElementById('i2').value;
var z= document.getElementById('i3').value;
var a= document.getElementById('i4').value;

var bt= document.getElementById('btn');
var da;

bt.onclick = function () {
da= (x[3] +y[2] +y[3] +y[0] +y[2] +x[6] +z[1]
+z[1] +z[0] +y[2] +z[2] +a[5]);


document.getElementById('di').innerHTML = da;
}

Enter on input text displays NAN what is wrong ?
April 3rd 20 at 18:49
2 answers
April 3rd 20 at 18:51
x, y, z, a is not an array, it can't fold.
when manipulating the string as an array you get a string, not a int
da= x + y + z + a or try to convert using parseInt
Yes, you are right, x, y, z, a is a string, not an array, but you can get a character from string by index - Elton27 commented on April 3rd 20 at 18:54
If I specify in the HTML input value a value all is displayed , but when I enter the page, other text displays NAN - heidi commented on April 3rd 20 at 18:57
you can see the text which is trying to lay down? - terence.Hansen94 commented on April 3rd 20 at 19:00


Enter:


operation



hero



the property



impact



To cipher


- heidi commented on April 3rd 20 at 19:03
@terence.Hansen94when enter the input value in all works , but I want to be able to enter on the website - heidi commented on April 3rd 20 at 19:06
What you're talking about looks like this
var btn = document.querySelector('#btn');
var di = document.querySelector('#di');

btn.onclick = function () {
 var x = document.querySelector('#i1').value;
 var y = document.querySelector('#i2').value;
 var z = document.querySelector('#i3').value;
 var a = document.querySelector('#i4').value;
 di.innerHTML = x[3] + y[2] + y[3] + y[0] + y[2] + x[6] + z[1] + z[1] + z[0] + y[2] + z[2] + a[5];
}

Problem. When you just enter something in the field, assuming only 1 character, there is of course no y[3] and in this case get a undefine + undefine - get NaN.

You need to consider additional testing, as an example the length of the string - terence.Hansen94 commented on April 3rd 20 at 19:09
April 3rd 20 at 18:53
You variables are initialized immediately when input empty, there is correspondingly undefined
Then you try to add 2 undefined. The second is converted to NaN and it turns out that NaN is displayed
On each click, see values.

Find more questions by tags JavaScript