我明白了:
var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];
我需要它是 2 个新数组 一个只有数字,另一个只有字符串
像这样:
var strArr = ["three", "2", "five", "ten", "111","forty", "33"];
var numArr = [1, 2, 33];
我应该怎么做?
最佳答案
您可以将 typeof
operator 与 filter
方法结合使用,该方法接受一个回调 函数作为参数。
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];
var numbers = arr.filter(function(item){
return typeof item == 'number';
});
var strings = arr.filter(function(item){
return typeof item == 'string';
});
console.log(numbers);
console.log(strings);
您可以使用 arrow
函数来实现轻型解决方案。
['number', 'string'].map(i => arr.filter(a => typeof a == i));
关于javascript - 过滤数组以便按数据类型对项目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341390/