str [0]和str.charAt(0)之间的区别 [英] Difference between str[0] and str.charAt(0)

查看:543
本文介绍了str [0]和str.charAt(0)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

str [0] str.charAt(0)之间有什么区别?我总是通过输入 str [i] 来访问特定字符,其中 i 是我想要的字符的索引访问(从0开始计算),但上周我对开源JS代码有了很好的概述,在我看到的每个项目中,人们都使用 charAt 方法。

What is the difference between str[0] and str.charAt(0)? I always access specific character by simply typing str[i], where i is the index of the character I want to access (counted from 0), but last week I had good overview of open source JS code, and in every single project I saw, people use charAt method.

这两种方式有什么区别吗?

Is there any difference between those two ways?

推荐答案

[] 是一种更原始​​的方式来访问所有类型的数组。

[] is a more primitive way of accessing all kind of arrays.

charAt()特定于字符串。

您可以使用 [] 访问任何数组的索引,但你只能在字符串上使用 charAt()

You can access the index of any array by using [], but you can only use charAt() on a string.

但是当单独使用字符串时,两者都是一个同样。

But when it comes to string alone, both are one and the same.

但你应该使用 charAt(),因为它在所有主流浏览器中都得到了很好的支持,括号表示法将在IE7中返回 undefined

But you should use charAt() because, it is well supported in all the major browsers, while the bracket notation will return undefined in IE7

此外,括号表示法是sim ply访问,而 charAt()进行一些验证并且不返回 undefined ,但会返回一个空字符串

Also, the bracket notation is simply accessed, while charAt() does some validation and doesn't return undefined, but will return an empty string ""

这篇关于str [0]和str.charAt(0)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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