Javascript:无法使用String.fromCharCode创建JSON对象以生成键和值

时间:2014-08-04 16:00:08

标签: javascript json

我正在尝试使用以下对象来修复文本区域元素中的粘贴上的字符映射以匹配字符。

var replacementMap = {
    String.fromCharCode(61607) : String.fromCharCode("9632"),  //solid box
    String.fromCharCode(61623) : String.fromCharCode("9679"),  //solid circle
    String.fromCharCode(61656) : String.fromCharCode("9654"),  //right arrow
    String.fromCharCode(61692) : String.fromCharCode("10003"), //checkmark
    String.fromCharCode(61558) : String.fromCharCode("10070")  //black diamond minus white X
};

从正则表达式调用此对象,以根据字符代码更改字符串中的字符,但当前firebug会抛出以下错误:

SyntaxError: missing : after property id
String.fromCharCode(61607) : String.fromCharCode("9632"),  //solid

2 个答案:

答案 0 :(得分:2)

您不能将函数/方法调用用作对象文字键。你会想要这样的东西:

var replacementMap = {};

replacementMap[ String.fromCharCode(61607) ] = String.fromCharCode("9632");  //solid box
replacementMap[ String.fromCharCode(61623) ] = String.fromCharCode("9679");

// etc.

答案 1 :(得分:2)

如果你只是想要编译对象,你可以这样做:

var replacementMap = {};

replacementMap[String.fromCharCode(61607)] = String.fromCharCode("9632");  //solid box
replacementMap[String.fromCharCode(61623)] = String.fromCharCode("9679");  //solid circle
replacementMap[String.fromCharCode(61656)] = String.fromCharCode("9654");  //right arrow
replacementMap[String.fromCharCode(61692)] = String.fromCharCode("10003"); //checkmark
replacementMap[String.fromCharCode(61558)] = String.fromCharCode("10070");  //black diamond minus white X

但他们是对的 - 它不是阵列! :)