函数'的参数是未定义的,但我调用它传递所有必要的参数

Function's parameters is Undefined but I called it passing all necessary arguments

本文关键字:参数 调用 未定义 函数      更新时间:2023-09-26

我有这段代码,我要做的是解析两个单词之间的内容,比如:"开始中间结束"应该返回中间。如果句子是"开始中间结束。Start middle2 end"应该返回一个包含"middle"answers"middle2"的数组。

问题是:

当我调用FindAll函数时,我得到一个未定义对象。我用来测试的Alert也说任何参数都等于Undefined Object

你可以在你的firebug上运行它,你会看到。

function findWithin(text, start, end, include) {
    "use strict";
    var stringExists = (text.indexOf(end) === -1),
        startPosition = text.indexOf(start),
        endPosition = text.indexOf(end),
        tMatch = [2];
    tMatch[0] = text.slice(endPosition + end.length, text.length);
    if (!stringExists) {
        if (include) {
            tMatch[1] = text.slice(startPosition, endPosition + end.length);
        } else {
            tMatch[1] = text.slice(startPosition + start.length, endPosition);
        }
    } else {
        tMatch[2] = false;
    }
    return tMatch;
}
function findAll(text, start, end, include) {
    "use strict";
    alert(toString(end));
    var findWithinVar = findWithin(text, start, end, include),
        occurrences = [],
        i = 0;
   // alert(toString(findWithinVar[2]));
    for (i; findWithinVar[2]; i++) {
        occurrences[i] = findWithinVar[1];
        findWithinVar = findWithin(text, start, end, include);
    }
    return occurrences;
}
var text = "Start middle end. Start middle end. Start middle end.",
    start = "Start",
    end = "end",
    result = findAll(text, start, end, false);

问题是您的toString方法。不是你想的那样。将end传递给alert()

alert(end);

您使用的toString()window.toString。我不知道这是否是一个标准方法,但它基本上是Object.prototype.toString的一个快捷方式。

当调用Object.prototype.toStirng时,它期望它的this值是某个对象,它将返回它的内部[[Class]]属性。因为您没有设置this值,它返回[object Undefined],因为您处于严格模式。


如果你这样做了:

toString.call(end)

它将返回[object String],这是正确的,但不是您想要的。