为什么String.prototype.match()返回null而不是空数组?

问题描述 投票:0回答:1

示例取自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的原因吗?

javascript regex
1个回答
0
投票

这就是EcmaScript标准中定义String.prototype.match的方式

  1. 21.1.3.11String.prototype.match ( regexp )
  2. 21.2.5.7RegExp.prototype [ @@match ] ( string )
  3. 21.2.5.2.2Runtime Semantics: RegExpBuiltinExec ( R, S )

简而言之:如果没有匹配项,则按标准返回null

© www.soinside.com 2019 - 2024. All rights reserved.