2016-07-27 39 views
4

爲什麼這樣的:使用「in」運算符時,何時是一個字符串對象?

console.log('length' in new String('test')) 

回報真正,而這一點:

console.log('length' in String('test')) 

拋出一個TypeError?

不能使用 '在' 運營商的測試搜索 '長度'

+1

看看[Explicit Coercion]的含義(https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md#explicit-強制)和[隱式強制](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md#implicit-coercion)。 – MarcoL

+0

@MarcoL不錯的參考! –

回答

2

JavaScript有字符串原語和字符串對象。 (對於數字和布爾值也是類似的。)在第一次測試中,您正在測試一個對象,因爲new String()創建了一個對象。在你的第二,你正在測試一個原語,因爲String(x)只是將x轉換爲字符串。你的第二個測試和寫作完全一樣console.log('length' in 'test');

in operator(你必須向下滾動一下)拋出一個類型錯誤,如果你在某個非物體上使用它;它的六個步驟下RelationalExpression第五:RelationalExpression in ShiftExpression

  • 如果Type(RVAL)不是Object,扔掉類型錯誤異常。
  • (這有些令我吃驚;大多數需要物體強制原始物體的東西,但不是in。)

    +0

    感謝您花時間回答使用規範作爲參考! –

    2

    嘗試:

    typeof String('test') -> "string" 
    typeof new String('test') -> "object" 
    

    in將與對象才能正常工作。

    2

    MDN

    的操作中,如果指定的屬性在 指定的對象返回true。 您必須在in運算符的右側指定一個對象。例如,對於 示例,您可以指定使用字符串構造函數創建的字符串 ,但不能指定字符串字面值。

    var color1 = new String("green"); 
    "length" in color1 // returns true 
    
    var color2 = "coral"; 
    // generates an error (color2 is not a String object) 
    "length" in color2 
    
    2
    var s_prim = 'foo'; //this return primitive 
    var s_obj = new String(s_prim);//this return String Object 
    
    console.log(typeof s_prim); // Logs "string" 
    console.log(typeof s_obj); // Logs "object" 
    

    MDN

    中操作者如果指定的屬性是在 指定對象返回true。

    "length" in s_obj // returns true  
    
        "length" in s_prim // generates an error (s_prim is not a String object) 
    

    在操作者只用於對象,數組

    相關問題