javascript - 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
不同的方式定义变量,但我总是得到“无效的字符串长度”错误。
我有什么错误吗?有没有一种特定的方法来创建我不知道的空白变量?
解决方案
有了这个
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 "
推荐阅读
- java - 如何将 JRadioButton 或 JCheckbox 数据保存到文件中
- javascript - 如何从 JavaScript 中的字符串中删除 *.*、*/*
- javascript - HTML/JS 中的条件自动更新日期
- rest - Jax rs 休息客户端 - 超时配置
- javascript - Slice into chunks and average (reduce) array in JS
- ios - 我可以在情节提要中使 ViewController 处于非活动状态吗?
- angular - Angular 4 获取使用 *ngIf 隐藏的元素的高度
- python-3.x - 安装后无法在 PyCharm (Jupyter) 中导入 Xgboost 包
- python - 如何在熊猫中创建叠加条图
- html - 垂直对齐两个按钮