爲什麼這樣的:使用「in」運算符時,何時是一個字符串對象?
console.log('length' in new String('test'))
回報真正,而這一點:
console.log('length' in String('test'))
拋出一個TypeError?
不能使用 '在' 運營商的測試搜索 '長度'
爲什麼這樣的:使用「in」運算符時,何時是一個字符串對象?
console.log('length' in new String('test'))
回報真正,而這一點:
console.log('length' in String('test'))
拋出一個TypeError?
不能使用 '在' 運營商的測試搜索 '長度'
JavaScript有字符串原語和字符串對象。 (對於數字和布爾值也是類似的。)在第一次測試中,您正在測試一個對象,因爲new String()
創建了一個對象。在你的第二,你正在測試一個原語,因爲String(x)
只是將x
轉換爲字符串。你的第二個測試和寫作完全一樣console.log('length' in 'test');
in
operator(你必須向下滾動一下)拋出一個類型錯誤,如果你在某個非物體上使用它;它的六個步驟下RelationalExpression第五:RelationalExpression in
ShiftExpression:
(這有些令我吃驚;大多數需要物體強制原始物體的東西,但不是in
。)
感謝您花時間回答使用規範作爲參考! –
嘗試:
typeof String('test') -> "string"
typeof new String('test') -> "object"
in
將與對象才能正常工作。
從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
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)
在操作者只用於對象,數組
看看[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
@MarcoL不錯的參考! –