简体   繁体   中英

Why won't the string concatenate in the loop?

 if (y.length==num){
              let m = y.toString();
              let h = "";
              let g = "";
              let n = "";
              for(let j=0;j<m.length;j++){
                n = m.charAt(j);
                if (n!=","){
                  g = h.concat(n);
                }
            }
            console.log(g)
          }

If an array's length is equal to an integer, then we're creating a variable of the string made of out the array as well as an arbitrary string h. Then we're looping through the string m, using charAt. The aim is to get rid of commas in the string and then consolidate chars not equal to a comma. However, the loop won't concatenate the new string. Do you guys happen to have any idea why?

h is initialized to the empty string, and never gets reassigned, so

var g = h.concat(n);

will always effectively mean

var g = n;

which is the current character being iterated over.

You might remove the g variable entirely, and reassign h instead:

 const num = 5; const y = ['a', 'b', ',', 'c,', 'd']; if (y.length==num){ let m = y.toString(); let h = ""; for(let j=0;j<m.length;j++){ let n = m.charAt(j); if (n!=","){ h = h.concat(n); } } console.log(h) } 

A much more readable option would be to join by the empty string (don't invoke toString , that'll add undesirable commas), and then use a regular expression to remove , s:

 const num = 5; const y = ['a', 'b', ',', 'c,', 'd']; if (y.length==num){ const cleaned = y .join('') .replace(/,/g, ''); console.log(cleaned); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM