gpt4 book ai didi

javascript - JS中解析数字时无限循环

转载 作者:行者123 更新时间:2023-12-02 21:32:57 25 4
gpt4 key购买 nike

我试图将一个列表拆分为包含数字或不包含数字的子列表,而不会像使用 split() 那样丢失任何数据。这非常尴尬,但我陷入了无限循环,而且我一生都无法找出这个错误。感谢您的帮助!

const parseArg = arg => {
const parsedList = [];
let pos, str;
let grabbingDigits = false;
while (arg.length != 0) {
pos = grabbingDigits ? arg.search(/\d/) : pos = arg.search(/^\d/);
str = arg.substring(0,pos);
arg = pos != -1 ? arg.substring(pos) : arg;
parsedList.push(str);
grabbingDigits = !grabbingDigits;
}
return parsedList;
}
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']

最佳答案

仅使用一个全局正则表达式可能会更容易:将数字与 \d+ 匹配。 、\D+ 匹配非数字:

const parseArg = arg => arg.match(/\d+|\D+/g);
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']

对于像原始代码这样更具编程性的方法,请在循环内确定从 arg (当前)开始的字符数。是数字或非数字,则 .slice适本地:

const parseArg = arg => {
const parsedList = [];
while (arg.length != 0) {
const thisLength = arg.match(/^\d/)
? arg.match(/^\d+/)[0].length
: arg.match(/^\D+/)[0].length;
parsedList.push(arg.slice(0, thisLength));
arg = arg.slice(thisLength);
}
return parsedList;
}
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']

关于javascript - JS中解析数字时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60573698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com