首页 > 解决方案 > 为什么 String.prototype.match() 返回 null 而不是空数组?

问题描述

示例取自MDN webdocs

var paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
var regex = /[A-Z]/g;
var found = paragraph.match(regex);

console.log(found); // will return an array of matches and returns null when nothing matches.

想知道在没有匹配项时返回 null 而不是 Empty Array 背后的原因吗?

标签: javascriptregex

解决方案


这就是String.prototype.matchEcmaScript 标准中的定义

  1. 21.1.3.11String.prototype.match(正则表达式)
  2. 21.2.5.7RegExp.prototype [@@match](字符串)
  3. 21.2.5.2.2运行时语义:RegExpBuiltinExec(R,S)

简而言之:如果没有匹配项 - 它null按标准返回。


推荐阅读