Javascript 如何从数组中返回所有字符串元素?
嘿,我是一个javascripter初学者,需要知道正确的方法。我需要这个函数只使用方法.filter将数组的所有字符串返回给我 所以它应该输出['Mike','23','elephant']Javascript 如何从数组中返回所有字符串元素?,javascript,arrays,string,methods,Javascript,Arrays,String,Methods,嘿,我是一个javascripter初学者,需要知道正确的方法。我需要这个函数只使用方法.filter将数组的所有字符串返回给我 所以它应该输出['Mike','23','elephant'] const array = [10, 'Mike', '23', NaN, 'elephant'] function stringsOnly(array) { const filteredStrings = array.filter((item) => { return i
const array = [10, 'Mike', '23', NaN, 'elephant']
function stringsOnly(array) {
const filteredStrings = array.filter((item) => {
return item.stringsOnly
})
return filteredStrings
}
stringsOnly()
您可以获取变量的类型并重新返回过滤后的数组 通过调用函数,您还需要移交数组
函数字符串(数组){
返回array.filter(item=>typeof item=='string');
}
常量数组=[10',Mike',23',NaN',elephant'];
log(stringsOnly(array))
[10',Mike',23',NaN',elephant'].filter(值=>typeof值==='string')
const onlyStrings=items=>items.filter(值=>typeof值=='string')
这正是我需要的,谢谢