此javascript return语句是什么意思?

时间:2019-10-02 07:06:44

标签: javascript return

请查看以下return语句:

sortedNotes() {
      return (
        this.notes &&
        this.notes.sort((a, b) => {
          const aDate = new Date(a.createdAt)
          const bDate = new Date(b.createdAt)
          return bDate - aDate
        })
      )
    }

是什么意思?仅仅是这样还不够:

sortedNotes() {
      return this.notes.sort((a, b) => {
          const aDate = new Date(a.createdAt)
          const bDate = new Date(b.createdAt)
          return bDate - aDate
        })
    }

更新:

更清楚地看一下这个:

return (foo && bar);

这是什么意思?如果foo为true,则返回bar?那呢:

return (bar && foo);

这里到底返回什么?

1 个答案:

答案 0 :(得分:2)

this.notes &&确保首先存在this.notes。如果它不存在,它将返回而不会引发错误(更准确地说,它将返回this.notes的假值-可能是undefined)。

如果无条件返回this.notes.sort,则如果this.notes不是数组,则会引发错误。例如:

class Notes {
  sortedNotes() {
    return (
      this.notes &&
      this.notes.sort((a, b) => {
        const aDate = new Date(a.createdAt)
        const bDate = new Date(b.createdAt)
        return bDate - aDate
      })
    )
  }
}

const n = new Notes();
// this.notes doesn't exist yet, so this doesn't do anything, but at least it doesn't throw an error:
n.sortedNotes();
console.log('done');

class Notes {
  sortedNotes() {
    return (
      this.notes.sort((a, b) => {
        const aDate = new Date(a.createdAt)
        const bDate = new Date(b.createdAt)
        return bDate - aDate
      })
    )
  }
}

const n = new Notes();
// Throws:
n.sortedNotes();
console.log('done');

因此,需要测试this.notes是否存在,以避免在调用this.notessortedNotes不存在时出错。

这可能只是拼写错误,但请确保某些内容遵循return语句,而不是普通的换行符-使用return this.notes.sort((a, b) => {或在括号中加上括号(之后,以避免ASI问题。 (否则,将不会返回任何内容)


return (foo && bar);

表示:评估foo。如果是事实,请评估bar并返回bar。否则,返回foo

return (bar && foo);

表示:评估bar。如果是事实,请评估foo并返回foo。否则,返回bar

在您的上下文中,一个更准确的最小示例是当尚不知道某个属性是否存在时。例如

return obj.fn()
如果obj未定义,

将抛出,而

return obj && obj.fn();

不会扔。

所有这些,这是要编写的 odd 代码。相反,进行显式测试会更具可读性,例如:

if (!obj) {
  return 'Not defined yet!';
} else {
  return obj.fn();
}
相关问题