Javascript 当使用“字符串”时,字符串何时为对象;在;操作人员
为什么会这样:Javascript 当使用“字符串”时,字符串何时为对象;在;操作人员,javascript,string,Javascript,String,为什么会这样: console.log('length' in new String('test')) 返回true,而: console.log('length' in String('test')) 抛出一个打字错误 无法使用“in”运算符在测试中搜索“length” 尝试: 中的仅适用于对象。中的 如果指定的属性位于 指定的对象。 必须在in运算符的右侧指定对象。对于 例如,可以指定使用字符串构造函数创建的字符串, 但不能指定字符串文字 从 如果指定的属性位于 指定的对象 In运算符仅
console.log('length' in new String('test'))
返回true,而:
console.log('length' in String('test'))
抛出一个打字错误
无法使用“in”运算符在测试中搜索“length”
尝试:
中的仅适用于对象。中的
如果指定的属性位于
指定的对象。
必须在in运算符的右侧指定对象。对于
例如,可以指定使用字符串构造函数创建的字符串,
但不能指定字符串文字
从
如果指定的属性位于
指定的对象
In运算符仅用于对象,数组具有字符串原语和字符串对象。在第一个测试中,您正在测试一个对象,因为newstring()
创建了一个对象。在第二个示例中,您正在测试一个原语,因为String(x)
只是将x
转换为字符串。您的第二个测试与编写console.log(“test”中的“length”)完全相同代码>
如果在非对象的对象上使用,则(必须向下滚动一点)抛出类型错误;这是RelationalExpression下六个步骤中的第五步:RelationalExpressionin
shiftePression:
如果Type(rval)不是Object,则抛出一个TypeError异常
(这有点出乎我的意料;大多数需要对象的东西都会将原语强制到对象,而不是
中的)看看JavaScript中和的含义。@MarcoL很好的参考资料!感谢您抽出时间以规范为参考回答问题!
typeof String('test') -> "string"
typeof new String('test') -> "object"
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"
"length" in s_obj // returns true
"length" in s_prim // generates an error (s_prim is not a String object)