匹配返回字符串而不是对象

发布于 2024-08-25 15:20:26 字数 335 浏览 2 评论 0原文

这个简单的正则表达式匹配在每个浏览器上返回一个字符串而不是一个对象,但最新的firefox...

        text = "language. Filename: My Old School Yard.avi. File description: File size: 701.54 MB. View on Megavideo. Enter this, here:"
    name = text.match(/(Filename:)(.*) File /);
    alert(typeof(name));

据我所知,匹配函数应该返回一个对象(数组)。 有人遇到过这个问题吗?

This simple regex matching returns a string instead of an object on every browser but the latest firefox...

        text = "language. Filename: My Old School Yard.avi. File description: File size: 701.54 MB. View on Megavideo. Enter this, here:"
    name = text.match(/(Filename:)(.*) File /);
    alert(typeof(name));

as far as i know this the match function is suppose to return an object (Array).
Has anyone come across this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念绕指尖 2024-09-01 15:20:26

RegExp match 方法确实返回数组,但 JavaScript 中的数组只是继承自 Array.prototype 的对象,例如:

var array = "foo".match(/foo/); // or [];,  or new Array();

typeof array; // "object"
array instanceof Array; // true
Object.prototype.toString.call(array); // "[object Array]"

typeof 运算符将返回 "object",因为它无法区分普通对象和数组。

在第二行中我使用 instanceof 运算符来证明该对象实际上是一个数组,但是该运算符具有 在跨框架环境中工作时的已知问题

在第三行中,我使用 Object.prototype.toString方法,该方法返回一个包含 [[Class]] 内部属性,该属性是一个指示对象类型的值,这是一种更安全的方法来检测对象是否为数组或不是。

The RegExp match method does return an array, but arrays in JavaScript are simply objects that inherit from Array.prototype, e.g.:

var array = "foo".match(/foo/); // or [];,  or new Array();

typeof array; // "object"
array instanceof Array; // true
Object.prototype.toString.call(array); // "[object Array]"

The typeof operator will return "object" because it can't distinguish between an ordinary object and an array.

In the second line I use the instanceof operator to prove that the object is actually an array, but this operator has known issues when working in cross-frame environments.

In the third line I use the Object.prototype.toString method, which returns a string that contains the [[Class]] internal property, this property is a value that indicates the kind of the object, a much safer way to detect if an object is an array or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文