Heim  >  Artikel  >  Web-Frontend  >  浅谈JavaScript中的字符编码转换问题_基础知识

浅谈JavaScript中的字符编码转换问题_基础知识

WBOY
WBOYOriginal
2016-05-16 15:51:031235Durchsuche

要获得字符的Unicode编码,可以使用string.charCodeAt(index)方法,其定义为:
  

  strObj.charCodeAt(index)


      index为指定字符在strObj对象中的位置(基于0的索引),返回值为0与65535之间的16位整数。例如:

   var strObj = "ABCDEFG";


   var code = strObj.charCodeAt(2); // Unicode value of character 'C' is 67


      如果index指定的索引处没有字符,则返回值为NaN。

 

      要将Unicode编码转换为一个字符,使用String.fromCharCode()方法,注意它是String对象的一个"静态方法",也就是说在使用前不需要创建字符串实例:


   

  String.fromCharCode(c1, c2, ...)


      它接受0个或多个整数,返回一个字符串,该字符串包含了各参数指定的字符,例如:


     

var str = String.fromCharCode(72, 101, 108, 108, 111); // str == "Hello"


讨论:


      Unicode包含了这个世界上很多书写语言的字符集,但别因为Unicode包含一个字符就期望这个字符能够在警告对话框、文本框或页面呈现时正常显示。如果字符集不可用,在页面将显示为问号或其它符号。一台典型的北美的计算机将不能在屏幕上显示中文字符,除非中文的字符集及其字体已经安装。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn