Skip to content
Advertisement

Why does javascript reads var as a string if i add ‘+’ to it?

I have field names in my firestore document as

videolink1-“some video link”

videolink2-“some video link”

videolink3-“some video link”

I am using a for loop to get all videolinks present in the document.

                if (doc.exists) {
                  
                   for (var i = 1; i == videocount; i++) { //videocount is 3

                    var data = doc.data();
                    var videolink = data.videolink+i;

  //creating new paragraph
                    var p = '<p class ="trackvideostyle">'+"Your Video Link : "+String(videolink)+'</p>';

                    document.getElementById("btn").insertAdjacentHTML('beforebegin', p);

                    }

But this for loop is creating var values which are being read as string and firestore is returning me NaN as I dont have these fields :

data.videolink+1

data.videolink+2   //Firestore is returning null as i dont have these document fields

data.videolink+3

How can I write for loop so that var values are created like this and firestore reads it as:

videolink1

videolink2

videolink3

Advertisement

Answer

I think you could try something like this,

var videolink = data[`videolink${i}`];

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement