我有一个JavaScript中的一维整数数组,想要从逗号分隔的字符串中添加数据,是否有简单的方法可以实现?
例如:var strVale = "130,235,342,124";
我有一个JavaScript中的一维整数数组,想要从逗号分隔的字符串中添加数据,是否有简单的方法可以实现?
例如:var strVale = "130,235,342,124";
这篇帖子中有很好的解决方案,但我想再添加一个。不建议使用filter
和map
,而是建议使用reduce
一次遍历所有项。
另外,我将与查找数字的正则表达式进行比较。请评估哪种方法适合您的需求。以下是例子:
const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1'
const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, [])
console.log(arrayOfNumbersA)
// => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers
// do work and if the number have characters before or after
// the numbers are removed from since they are treated like NaN.
// Note: in this case the comma is the delimiting each number that will be evaluated in the reduce
const arrayOfNumbersB = strA.match(/[\d.]+/g).map(Number)
console.log(arrayOfNumbersB)
// => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers
// are transformed to positives and if the number have characters before or after
// the numbers placed any way.
//Note: that in this case the regex is looking for digits no matter how they are separated.
// FYI: seeing all the steps using the reduce method
const arrayOfNumbersC = strA.split(',').reduce((acc, val) => {
if(val && !Number.isNaN(+val)) {
acc.push(+val)
}
return acc
}, [])
console.log(arrayOfNumbersC)
// => [1, 0, -2, 21, 8.1]