首页 > 解决方案 > JavaScript没有创建一个由唯一的空白子字符串组成的字符串?

问题描述

所以我正在创建一个函数,它应该创建一个由 x 个空格组成的字符串,具体取决于作为函数参数传递的数字。问题是当我运行代码时,我收到错误“无效的字符串长度”,所以基本上不将空格算作字符。

请在下面查看我的代码:

    function ajustarTexto(str, num) {
      let len = str.length;
      newstr = str;
      whtspc = (" ");
      if (len < num){
        for (let i = 0; i >= 0 ; i++){
          newstr = whtspc += whtspc;
        };
      }else if (len > num) {
          newstr.splice(num);
      };
      
      return newstr;
    };
    
    
    
    
    console.log(ajustarTexto("", 3)) // " " 
    console.log(ajustarTexto("hola", 2)) // "ho" 
    console.log(ajustarTexto("Hola", 0)) // "" 
    console.log(ajustarTexto("Hola", 5)) // "Hola "

我试图以whtspc不同的方式定义变量,但我总是得到“无效的字符串长度”错误。

我有什么错误吗?有没有一种特定的方法来创建我不知道的空白变量?

标签: javascriptstringsubstringwhitespace

解决方案


有了这个

newstr = whtspc += whtspc;

whtspc每次迭代都会将字符串的长度加倍。该表达式等价于:

whtspc += whtspc;
newstr = whtspc;

因此,在循环内部,whtspc从长度 1 开始,到 2,然后是 4,然后是 8,依此类推。最终,没有更多空间并引发错误。

padEnd如果输入字符串的长度恰好小于num

function ajustarTexto(str, num) {
  return str.slice(0, num).padEnd(num, ' ');
}
console.log(ajustarTexto("", 3)) // " " 
console.log(ajustarTexto("hola", 2)) // "ho" 
console.log(ajustarTexto("Hola", 0)) // "" 
console.log(ajustarTexto("Hola", 5)) // "Hola "


推荐阅读