[英]How do I extract numbers from a string in JavaScript without using regular expressions?
例如,我有一個字符串“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, 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),但它實際上仍然是線性的,因為循環遍歷同一個數組,一個循環從另一個停止的地方開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.