我正在尝试使用.filter只返回数组中的字符串元素,但我不太确定该怎么做

时间:2019-06-20 19:47:17

标签: javascript

我正在尝试解决一系列问题,其中一个问题需要我编写一个函数,该函数返回多个数组中的所有字符串元素。但是,我不太确定如何正确使用过滤器。

这是我解决问题的尝试。

function stringsOnly(array) {

  array.filter(function(array) {
    return (typeof array === 'string') && !!array

  })
}

这些是我试图过滤并仅返回字符串('')的数组。

describe('stringsOnly', () => {
  it('should return only the strings of an array', () => {

    expect(stringsOnly([10, 'Mike', '23', NaN, 'elephant'])).to.deep.equal(['Mike', '23', 'elephant'])

    expect(stringsOnly([{}, [], 99, false])).to.deep.equal([])

    expect(stringsOnly(['I', 'am', 'the', 'eggman'])).to.deep.equal(['I', 'am', 'the', 'eggman'])

  })
})

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您不会在stringOnly函数中返回filter方法的结果。

function stringsOnly(array) {
  return array.filter(function(elem) {  // notice the return at the beginning of this line
    return (typeof elem === 'string') 
  })
}