JavaScript 很靈活,也提供了不少原生方法。要訪問字符串中的單個字符,主要有兩種方式:數組索引和 charAt() 函數。
在 JavaScript 中字符串可以被當作數組處理,因此可以用下標訪問單個字符:
<script type="text/javascript">
var str = "hello world";
console.log(str[0]); // 輸出 h
</script>
<script type="text/javascript">
var str = "hello world";
console.log(str.charAt(1)); // 輸出 e
</script>
1. 超出範圍的返回值不同。使用 string[index],索引超出範圍時返回 undefined;使用 charAt(index),超出範圍時返回空字符串。
2. 兼容性不同。string[index] 在 IE6~8 下會返回 undefined,也就是說這三代並不支持這種寫法;而 charAt(index) 經測試在 IE6~8 下也能正常返回值。
如果不需要考慮 IE6~8,兩種寫法隨便用,性能差異微乎其微。但如果還得照顧老 IE,建議用 charAt(),安全又省心。