開心生活站

位置:首頁 > IT科技 > 

js,charcodeat

IT科技1.31W

1、js中charcodeat簡介:

charCodeAt()方法返回的是位於指定位置的字符的編碼。

charCodeAt() 方法可返回指定位置的字符的 Unicode 編碼。這個返回值是 0 - 65535 之間的整數。

2、語法:

stringObject.charCodeAt(index)

3、補充說明:

方法 charCodeAt() 與 charAt() 方法執行的操作相似,只不過前者返回的是位於指定位置的字符的編碼,而後者返回的是字符子串。
字符串中第一個字符的下標是 0。如果 index 是負數,或大於等於字符串的長度,則 charCodeAt() 返回 NaN。

js charcodeat

舉例:

一個簡單的函數將字符串中的每一個字符轉爲Unicode

<!DOCTYPE html>

<html>

<head>

 <meta charset="UTF-8">

<title>Title</title>

</head>

<body>

<script>

//將字符串的每一個字符轉爲Unicode號

js charcodeat 第2張

function encode(str) {

var arr = [];

for(var i=0;i<str.length;i++){

arr.push(str.charCodeAt(i));

}

return arr.join("");

}

console.log(encode("小明isgood"));

</script>

</body>

</html>

標籤:charcodeat js