![]() |
忐忑的马克杯 · Python3 字典 copy()方法 | ...· 1 年前 · |
![]() |
销魂的瀑布 · bootstrap导航栏的自动折叠隐藏-掘金· 1 年前 · |
![]() |
不拘小节的马克杯 · C++调用libcurl开源库实现邮件的发送 ...· 1 年前 · |
![]() |
有腹肌的玉米 · No ongoing ...· 2 年前 · |
![]() |
跑龙套的橡皮擦 · .Net EF Core千万级数据实践 - 墨天轮· 2 年前 · |
我有一个由字符串和数字组成的数组。我需要对数字进行排序,或者更好的是只提取另一个数组中的数字。示例如下:
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
我需要这样做
const filtered = [23456, 34, 23455]
我使用split(‘')方法用逗号分隔它们,但不知道如何将它们过滤为JS,它们都是字符串。
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
var result=[];
myArr.forEach(function(v){
arr=v.match(/[-+]?[0-9]*\.?[0-9]+/g);
result=result.concat(arr);
const filtered = result.map(function (x) {
return parseInt(x, 10);
console.log(filtered)
这可能是一种可能的解决方案,
请参阅MDN了解
map()
替换()
trim()
和
split()
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
filtered = myArr[0].replace(/\D+/g, ' ').trim().split(' ').map(e => parseInt(e));
console.log(filtered);
或者
const regex = /\d+/gm;
const str = `Prihodi 23456 danaci 34 razhodi 23455 I drugi`;
let m;
const filter = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
filter.push(parseInt(match))
console.log(filter);
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
const reduced = myArr[0].split(' ').reduce((arr, item) => {
const parsed = Number.parseInt(item)
if(!Number.isNaN(parsed)) arr.push(parsed)
return arr
}, [])
console.log(reduced)
你可以用简单的
和
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
const result = myArr[0].match(/\d+/gi).map(Number);
console.log(result);
![]() |
忐忑的马克杯 · Python3 字典 copy()方法 | 菜鸟教程 1 年前 |
![]() |
销魂的瀑布 · bootstrap导航栏的自动折叠隐藏-掘金 1 年前 |
![]() |
跑龙套的橡皮擦 · .Net EF Core千万级数据实践 - 墨天轮 2 年前 |