例如,我有一个字符串"asdf123d6lkj006m90"我需要下面的结果[123,6,0,0,6,90]。我试着:
let str = "asdf123d6lkj006m90"
let func = function(inputString){
let outputArray = []
let currentNumber = ""
for(let element of inputString){
if(Number(element)||element == 0){
outputArray.push(Number(element))
}
}
return(outputArray)
}
console.log(func(str))
但是它返回[1,2,3,6,0,0,0,6,9,0]我怎样才能收到正确的号码?
当你应该检查接下来的几个字符时,你正在一次查看每个字符。
const str = "asdf123d6lkj006m90";
console.log(numbers(str));
function numbers(str) {
const nums = []; // create an array with the numbers
for(let i = 0; i < str.length; i++) {
// in your example you want preceding 0s to be their own number
if(str[i] == 0) {
nums.push(0);
continue;
}
let current = ""; // add to our string
while(!isNaN(str[i])) {
// as long as the character can be converted to a number
current += str[i++];
}
// if there were any numbers added
if(current.length)
nums.push(+current);
}
return nums;
}
注意,虽然这看起来像O(n^2),因为嵌套循环,它实际上仍然是线性的,因为循环遍历同一个数组,一个从另一个离开的地方开始。