轉(zhuǎn)換方法:1、利用split()方法將字符串轉(zhuǎn)為字符數(shù)組;2、遍歷字符數(shù)組,利用charCodeAt()和toString()方法將每個字符元素轉(zhuǎn)為二進(jìn)制值;3、使用join()方法拼接數(shù)組元素,轉(zhuǎn)為完整的二進(jìn)制值即可。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
javascript將字符串轉(zhuǎn)為二進(jìn)制
-
將字符串轉(zhuǎn)為字符數(shù)組
-
遍歷字符數(shù)組,使用charCodeAt()將每個字符元素轉(zhuǎn)為ascii碼
-
使用toString(2)將ascii碼元素轉(zhuǎn)為二進(jìn)制
-
使用join()拼接數(shù)組元素,轉(zhuǎn)為二進(jìn)制字符串。
實現(xiàn)代碼:
function strToBinary(str){ var result = []; var list = str.split(""); for(var i=0;i<list.length;i++){ if(i != 0){ result.push(" "); } var item = list[i]; var binaryStr = item.charCodeAt().toString(2); result.push(binaryStr); } return result.join(""); } console.log(strToBinary("我們")); //110001000010001 100111011101100
【