JavaScript访问字符串字符作为数组 [英] JavaScript access string chars as array

查看:100
本文介绍了JavaScript访问字符串字符作为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做:

var myString="Hello!";
alert(myString[0]); // shows "H" in an alert window

或者是否应该使用charAt(0)或substr(0,1)?
是没关系我的意思是它适用于大多数浏览器,是否有最佳实践建议,否则等等。

Or should it be done with either charAt(0) or substr(0,1)? By "is it ok" I mean will it work on most browsers, is there a best practice recommandation that says otherwise etc.

谢谢。

推荐答案

使用 charAt 可能是最好的主意,因为它传达了你的意图代码最准确。为单个字符调用 substr 绝对是一种矫枉过正。

Using charAt is probably the best idea since it conveys the intent of your code most accurately. Calling substr for a single character is definitely an overkill.

alert(myString.charAt(0));

这篇关于JavaScript访问字符串字符作为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆