我想爲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