すべての文字列を検索し、検索したい単語のインデックスを返すStringオブジェクトに関数を追加します。 startIndex
パラメータを使用しないと、この文typeof startIndex !== "undefined"
はstartIndex
なしで機能するため、2番目のエラーは発生しません。私を訂正し、助けてくれてありがとう。TypeErrorモジュールのステートメントは、2番目のパラメータを指定しないで関数を動作させません。
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、あなたがそれを実行しているブラウザを出力します –
OPは彼がスローを打っていると言っていると思いますが、2番目のパラメータがないときは期待していません。 – rasmeister
'startIndex = startIndex ||を実行しているとします。 0 'の場合、typeof startIndex!== "undefined" 'は常にtrueになります – Bergi