我想为String对象添加一个函数,它搜索所有字符串并返回我们想要查找的字的索引。当我不使用startIndex
参数时,它不应该抛出第二个错误,因为这个语句typeof startIndex !== "undefined"
让这个函数在没有startIndex
的情况下工作。请纠正我,并感谢您的帮助。TypeError模块中的语句不让函数无第二个参数
String.prototype.allIndexOf = allIndexOfFunction;
function allIndexOfFunction(string, startIndex) {
startIndex = startIndex || 0
var indexArr = [];
var sIndex = 0;
var baseString = this.concat();
if (typeof string === "string" && typeof startIndex === "number" && startIndex >= 0) {
while(sIndex !== -1){
sIndex = baseString.indexOf(string, startIndex);
if(sIndex !== -1){
indexArr.push(sIndex);
startIndex = startIndex + sIndex +1;
}
}
}
try {
if (typeof string !== "string") {
throw "First parameter must be a string type";
}
else if (typeof startIndex !== "number" || typeof startIndex !== "undefined") {
throw "Second parameter must be a number type";
}
else if (startIndex <= 0) {
throw "Second parameter must be equal or bigger than 0";
}
} catch(err) {
console.log(err);
}
return indexArr;
}
//TEST
var a = "Lorem ipsum dolor sit Buzz, consectetur Buzz elit. Quod vero voluptatibus Buzz error deserunt libero, Buzz incidunt Buzz facere! A!";
var test = a.allIndexOf("Buzz");
console.log("Searching indexes of \"Buzz\" word in string -> " + a);
console.log(test);
我没有通过运行该脚本收到任何类型的错误http://jsbin.com/qehasupuru/edit?html, JS,控制台,输出你正在运行它的那个浏览器 –
我认为OP是说他正在击中投掷,但没有期望当没有第二个参数。 – rasmeister
鉴于你正在做'startIndex = startIndex || 0',条件'typeof startIndex!==“undefined”'将始终为真 – Bergi