信不信由你,JavaScript的对象键总是
strings (是或
另请参阅Symbols ()
如果将this answer (.字符串以外的值作为键传递,则会首先强制将其转换为字符串。 因此…
var map={};
映射[ null ]=3;
映射[ null ];
你实际上设定了地图[“null”]。 注意:
console.log (map [ ' null ' ]===map [ null ] );//真
因此,在TypeScript中,他们积极地决定onlyallowthestringornumbertypeasindexsignatures .大多数情况下,想要使用null等为对象编制索引的人是错误的
就你而言,你可以:
functionbuildinversemap (源:阵列) : ([密钥:字符串] :编号)。
varinversemap : { [ key : string ] : number }={ };
for(letI=0; i source.length; I ) {
inverse map [ string ] [ source [ I ] ]=I; //coerce to string yourself
}
返回反转映射;
}
请注意我们如何将自己与source [i]联系起来。 这让TypeScript很高兴。 如果你记得用String ()包装钥匙,只要你能使用空值,它就应该适合你:
constinversemap=buildinversemap ([ ' a '、' b '、null、' c'];
常数索引=inverse map [ ' a ' ];
constnullindex=inverse map [ string ];
希望你能帮助我! 祝你好运。