0

我在 stackoverflow 上找到了这个有用的代码片段:

Array.prototype.clean = function(deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {         
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};

我用它从我当前移植到 Firefox 的 chrome 扩展中的数组中删除空值。我像这样使用ist:

foobar = foo.concat(bar).clean('').toString();

在 chrome 中运行良好,但在 Firefox 中我得到一个 TypeError:

TypeError: foo.concat(...).clean is not a function

有什么建议可能是什么问题?

//编辑//

foo 和 bar 是数组, foo 来自一个 json,解析如下:

var json = {property: 'a,b,c,d,e,f,g'};
json = json.property.split(',');

和来自一个文本区域的栏,它被解析如下:

function digestTextField (string) {
    // takes string of format "a, b , c", trims spaces, converts to lower case
    var rawText = document.getElementById(string + 'Events').value,
        digestedText = rawText.split(','),
        i;

    for (i = 0; i < digestedText.length; i += 1) {
        digestedText[i] = digestedText[i].toLowerCase()
                            .replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }
    return digestedText;
}

然后在调用 .clean('') 之前将两者都保存到 simpleStorage 并从中读取。

4

1 回答 1

0

There is no problem in the code posted, maybe you add clean to prototype after calling it? The following works in a xul application:

function jsdump(str) {
  Components.classes['@mozilla.org/consoleservice;1']
            .getService(Components.interfaces.nsIConsoleService)
            .logStringMessage(str);
}
Array.prototype.clean = function(deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {         
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};
var foo = {property: 'a,b'};
foo = foo.property.split(',');
var bar="5,6,,7,".split(",");

jsdump("Array has clean:"+Array.prototype.hasOwnProperty("clean"));
jsdump("is foo an array:"+(foo instanceof Array));
jsdump("is bar an array:"+(bar instanceof Array));
jsdump(foo.concat(bar).clean('').toString());

in defaults\preferences\prefs.js:

pref("browser.dom.window.dump.enabled", true);
pref("javascript.options.showInConsole", true);
pref("javascript.options.strict", true);
pref("nglayout.debug.disable_xul_cache", true);
pref("nglayout.debug.disable_xul_fastload", true);

Starting the application with:

firefox --app application.ini -jsconsole
于 2013-07-12T00:16:12.000 回答