简体   繁体   English

为什么字符串不能在循环中连接?

[英]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. 如果数组的长度等于整数,则我们将创建由数组组成的字符串的变量以及任意字符串h。 Then we're looping through the string m, using charAt. 然后,我们使用charAt遍历字符串m。 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 h初始化为空字符串,并且永远不会重新分配,因此

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: 您可能会完全删除g变量,而是重新分配h

 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: 一个更可读的办法是join由空字符串(不调用toString ,这会增加不良逗号),然后用正则表达式来去除, S:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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