2016-02-11 51 views
0

我測試了我的.indexOf的實現,它似乎可以在我的測試用例上工作,但我已經看到了其他解決方案,它們在if條件array[i] === elem && notFound === -1中添加了它們。第二種情況的目的是什麼?這是我的版本:這是.indexOf的正確實現嗎? Javascript

var indexOf = function (array, elem) { 
    var notFound = -1; 
    for (var i = 0; i < array.length; i++) { 
    if (array[i] === elem) {return i;} 
    } 
    return notFound; 
} 
+0

您是否正在嘗試創建一個'array.contains(string)'類似的函數? –

+5

這裏不需要添加'&& notFound === -1',它永遠不會是-1。如果需要,可以刪除該變量並在for循環後返回-1。 – IrkenInvader

+0

輸入值更好地檢查錯誤的值。 –

回答

0

你的實現似乎沒什麼問題。

我懷疑額外的檢查是在函數的一個版本中,當它找到一個匹配時不會跳出循環。當它發現匹配時,它會設置notFound = i;,並保持循環(不必要);當循環完成時,它返回notFound。測試notFound === -1是否阻止它在發現第二個匹配時更新變量。

如果不是這樣,那麼如果您實際上發佈了一個使用您顯示的檢查的實現示例,將會有所幫助。這可能只是一個錯誤 - 僅僅因爲你在互聯網上發現了代碼,並不意味着它是正確的。

-1

採取看看下面的填充工具(from mdn):

// Production steps of ECMA-262, Edition 5, 15.4.4.14 
// Reference: http://es5.github.io/#x15.4.4.14 
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(searchElement, fromIndex) { 

    var k; 

    // 1. Let o be the result of calling ToObject passing 
    // the this value as the argument. 
    if (this == null) { 
     throw new TypeError('"this" is null or not defined'); 
    } 

    var o = Object(this); 

    // 2. Let lenValue be the result of calling the Get 
    // internal method of o with the argument "length". 
    // 3. Let len be ToUint32(lenValue). 
    var len = o.length >>> 0; 

    // 4. If len is 0, return -1. 
    if (len === 0) { 
     return -1; 
    } 

    // 5. If argument fromIndex was passed let n be 
    // ToInteger(fromIndex); else let n be 0. 
    var n = +fromIndex || 0; 

    if (Math.abs(n) === Infinity) { 
     n = 0; 
    } 

    // 6. If n >= len, return -1. 
    if (n >= len) { 
     return -1; 
    } 

    // 7. If n >= 0, then Let k be n. 
    // 8. Else, n<0, Let k be len - abs(n). 
    // If k is less than 0, then let k be 0. 
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); 

    // 9. Repeat, while k < len 
    while (k < len) { 
     // a. Let Pk be ToString(k). 
     // This is implicit for LHS operands of the in operator 
     // b. Let kPresent be the result of calling the 
     // HasProperty internal method of o with argument Pk. 
     // This step can be combined with c 
     // c. If kPresent is true, then 
     // i. Let elementK be the result of calling the Get 
     //  internal method of o with the argument ToString(k). 
     // ii. Let same be the result of applying the 
     //  Strict Equality Comparison Algorithm to 
     //  searchElement and elementK. 
     // iii. If same is true, return k. 
     if (k in o && o[k] === searchElement) { 
     return k; 
     } 
     k++; 
    } 
    return -1; 
    }; 
} 
+0

如果答案可以幫助答案,那麼答案並不是真的應該依賴於外部鏈接,而且「共同鏈接答案」幾乎總是不合適的。您可能希望將其作爲評論。 –