返回一个空数组而不是null

时间:2019-06-23 13:47:05

标签: javascript

我想返回一个空数组。但是,它始终返回null。如何在我的代码中解决

我希望在这种情况下,提及数组返回空白,但它会一直返回空值

function getTweetData(tweet) {
  let hashtag = tweet.match(/#\w+/g)
  let atSign = tweet.match(/@\w+/g)

  let tweetObj = {
    tags: hashtag,
    mentions: atSign,
    tagCount: 0,
    mentionCount: 0,
    length: tweet.length
  }

  if (tweet.match(/#/g))
    tweetObj.tagCount++

  if (tweet.match(/@/g))
    tweetObj.mentionCount++

  console.log(tweetObj)
  return tweetObj
}

测试

it('Should increase the count of tags', () => {
    expect(getTweetData('My awesome tweet about #coding')).to.eql({ tags: ['#coding'], mentions: [], tagCount: 1, mentionCount: 0, length: 30 })
  });

2 个答案:

答案 0 :(得分:2)

您可以修改:

let atSign = tweet.match(/@\w+/g)

收件人:

let atSign = tweet.match(/@\w+/g) || []

在您的正则表达式返回null的情况下,添加|| []将为atSign分配一个空数组

答案 1 :(得分:1)

您可以这样做:

let hashtag = tweet.match(/#\w+/g) || []
let atSign = tweet.match(/@\w+/g)  || []
相关问题