为什么匹配的子字符串返回“未定义”在JavaScript中? [英] Why is a matched substring returning "undefined" in JavaScript?

查看:134
本文介绍了为什么匹配的子字符串返回“未定义”在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 在JavaScript中使用一些正则表达式时,我遇到了一个奇怪的行为(Firefox 3在Windows上) var str =format_%A; 
var format = /(?:*|s)format_(.*?)(?:\s|$)/.exec(str);

console.log(format); // [format_%A,%A]
console.log(format [0]); //format_undefined
console.log(format [1]); //未定义

正则表达式没有任何问题。正如您所看到的,它已经匹配了第一个 console.log 调用中的正确部分。



Internet Explorer 7和Chrome都表现得如预期: format [1] 返回%A(好吧,Internet Explorer 7正确地做了一些事情是有点意外的...) / b>

这是Firefox中的一个bug,还是一些我不知道的功能?



  console.log(我的名字是%A,John); //我的名字是John

参见 console.log()文档了解详情。 %A和任何其他未公开的占位符似乎都和%o一样。


I came across a strange behaviour when doing some regular expressions in JavaScript today (Firefox 3 on Windows Vista).

var str = "format_%A";
var format = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(str);

console.log(format);    // ["format_%A", "%A"]
console.log(format[0]); // "format_undefined"
console.log(format[1]); // Undefined

There's nothing wrong with the regular expression. As you can see, it has matched the correct part in the first console.log call.

Internet Explorer 7 and Chrome both behave as expected: format[1] returns "%A" (well, Internet Explorer 7 doing something right was a bit unexpected...)

Is this a bug in Firefox, or some "feature" I don't know about?

解决方案

This is because console.log() works like printf(). The first argument to console.log() is actually a format string which may be followed with additional arguments. %A is a placeholder. For example:

console.log("My name is %A", "John"); // My name is "John"

See console.log() documentation for details. %A and any other undocumented placeholders seem to do the same as %o.

这篇关于为什么匹配的子字符串返回“未定义”在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆