代码之家  ›  专栏  ›  技术社区  ›  Pablo

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

  •  0
  • Pablo  · 技术社区  · 14 年前

    这个简单的regex匹配返回一个字符串,而不是每个浏览器上的一个对象,除了最新的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));
    

    据我所知,match函数假定返回一个对象(数组)。 有人遇到这个问题吗?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Christian C. Salvadó    14 年前

    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]] 内部属性,此属性是指示 友善的 对于对象,检测对象是否是数组的一种更安全的方法。