JavaScript访问字符串字符作为数组 下载本文

内容发布更新时间 : 2024/6/28 13:58:50星期一 下面是文章的全部内容请认真阅读。

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

JavaScript 访问字符串字符作为数组

2010/10/29 43430 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(0)还是 substr(0,1)?通过“它没关系”我的意思是它适用 于大多数浏览器,是否有最佳实践建议,否则等等。 Thank you. 谢谢。 36

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.

使用 charAt 可能是最好的主意,因为它最准确地传达了代码的意图。为单个字符 调用 substr 绝对是一种矫枉过正。 alert(myString.charAt(0)); 41

Accessing characters as numeric properties of a string is non-standard prior to

ECMAScript 5 and doesn’t work in all browsers (for example, it doesn’t work in IE 6 or 7). You should use myString.charAt(0) instead when your code has to work in non- ECMAScript 5 environments. Alternatively, if you’re going to be accessing a lot of characters in the string then you can turn a string into an array of characters using its split() method:

在 ECMAScript 5 之前,将字符作为字符串的数字属性进行访问是非标准的,并且 在所有浏览器中都不起作用(例如,它在 IE 6 或 7 中不起作用)。当代码必须在非 ECMAScript 5 环境中工作时,应该使用 myString.charAt(0)。或者,如果您要访问 字符串中的大量字符,则可以使用 split()方法将字符串转换为字符数组: var myString = “Hello!”;var strChars = myString.split(““);alert(strChars[0]); 1 2018 answer: Yes it is OK to access strings like arrays.

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

2018 回答:是的,可以访问像数组这样的字符串。

The syntax is clear and concise. IE6 and IE7 are long gone. I see no reason not to use it.

语法清晰简洁。 IE6 和 IE7 早已不复存在。我认为没有理由不使用它。 tips:感谢大家的阅读,本文由我司收集整编。仅供参阅!