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

时间:2010-03-22 07:02:49

标签: javascript function match matching

这个简单的正则表达式匹配在每个浏览器上返回一个字符串而不是一个对象,但最新的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));

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

1 个答案:

答案 0 :(得分:1)

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运算符来证明对象实际上是一个数组,但是当在跨框架环境中工作时,此运算符具有known issues

在第三行中,我使用Object.prototype.toString方法,该方法返回包含[[Class]]内部属性的字符串,此属性是一个值,表示种类 object,一种检测对象是否为数组的更安全的方法。