[英]How do I extract numbers from a string in JavaScript without using regular expressions?
For example, I have a string "asdf123d6lkj006m90" and I need the following result [123, 6, 0, 0, 6, 90].例如,我有一个字符串“asdf123d6lkj006m90”,我需要以下结果 [123, 6, 0, 0, 6, 90]。 I tried:
我试过了:
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))
But it returns [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ] How do I receive the correct numbers?但它返回 [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ] 我如何收到正确的数字?
You're looking at each character at a time, when you should be checking the next few as well.您一次查看每个字符,同时您还应该检查接下来的几个字符。
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; }
And note, while this looks like O(n^2) because of the nested loop, it's actually still linear because the loops are traversing the same array and one picks up where the other left off.请注意,虽然由于嵌套循环,这看起来像 O(n^2),但它实际上仍然是线性的,因为循环遍历同一个数组,一个循环从另一个停止的地方开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.