JS-JavaScript String 对象-string对象方法1:fromCharCode()、charCodeAt()

1.fromCharCode(): 可接受一个指定的 Unicode 值,然后返回一个字符串。

  1). 语法:String.fromCharCode(n1n2, ..., nX)  (n1n2, ..., nX : 必需。一个或多个 Unicode 值,即要创建的字符串中的字符的 Unicode 编码。)

   注意:该方法是 String 的静态方法,字符串中的每个字符都由单独的 Unicode 数字编码指定。使用语法: String.fromCharCode()。 

<script>
//将 Unicode 编码转为一个字符:

 var n = String.fromCharCode(65);

 console.log(n)     //A


//将 Unicode 编码转换为一个字符串:

 var n1 = String.fromCharCode(72,69,76,76,79);

 console.log(n1)     //HELLO

</script>

  

  


 

2.charCodeAt():返回指定位置的字符的 Unicode 编码

1).语法:string.charCodeAt(index)(index:必需。表示字符串中某个位置的数字,即字符在字符串中的下标。)

2).字符串中第一个字符的位置为 0, 第二个字符位置为 1,以此类推。

3).返回值类型:Number (返回在指定的位置的字符的 Unicode 编码)

<script>
//返回字符串第一个字符的 Unicode 编码:

var str = "HELLO WORLD";

var n = str.charCodeAt(0);

console.log(n)    //72



//返回字符串中最后一个字符的 Unicode 编码:

var str1 = "HELLO WORLD";

var n1 = str.charCodeAt(str1.length-1);

console.log(n1)    //68

</script>

  

  

posted @ 2018-11-24 14:15  MiniDuck  阅读(560)  评论(0编辑  收藏  举报