在JavaScript中阅读df['dataDiv'] = df['data'] / df.groupby((df['T'] == 0).cumsum())['data'].transform('first')
的文档,并在一些环境(Chrome,Firefox,Node.js)中进行测试,我意识到我对隐式字符串转换的理解是有缺陷的。< / p>
我总是认为在尝试转换为字符串时调用了对象的Symbol
方法,并且如果该函数没有返回基元,那么它调用了对象& #39; s toString()
方法,如果那不起作用,则会输入错误。但是,此解释无法涵盖toPrimitive()
投掷的TypeError
:
Symbol
&#13;
var sym = Symbol("test");
try {
console.log(sym + "ing");
} catch (error) {
console.error(error);
}
但很明显TypeError: Cannot convert a Symbol value to a string
有一个有效的Symbol
方法。那么为什么不打电话呢?
答案 0 :(得分:5)
在进行隐式字符串转换时,调用对象toString
方法是正确的。但是,as the spec states,符号上的隐式字符串转换会导致TypeError
。
作为Dr. Axel Rauschmayer put it:
鉴于字符串和符号都可以是属性键,您希望保护人们不会意外地将符号转换为字符串。