string.charAt(x)或string [x]? [英] string.charAt(x) or string[x]?

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

问题描述

有什么理由我应该使用 string.charAt(x)而不是括号表示法 string [x]

Is there any reason I should use string.charAt(x) instead of the bracket notation string[x]?

推荐答案

// Bracket Notation
"Test String1"[6]

// Real Implementation
"Test String1".charAt(6)

出于这些原因,使用括号是个坏主意(来源):

It is a bad idea to use brackets, for these reasons (Source):


此表示法不起作用IE7。
第一个代码片段将在IE7中返回
undefined。如果您碰巧使用
字符串括号表示所有
超过您的代码,并且您希望将
迁移到 .charAt(pos) ,这是一个真正的痛苦:
在您的代码
中使用括号并且没有简单的方法来检测
是否为字符串或
数组/对象。

This notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to .charAt(pos), this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.

您无法使用此表示法设置字符。由于没有任何类型的
警告,这实在令人困惑且
令人沮丧。如果你使用
.charAt(pos)函数,你不会想要

You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the .charAt(pos) function, you would not have been tempted to do it.

基本上,它是一种未在所有浏览器中完全实现的快捷符号。

Basically, it's a shortcut notation that is not fully implemented across all browsers.

注意,你是无法使用任何一种方法编写字符。但是,使用 .charAt()函数可以更容易理解该功能,在大多数语言中,该函数是只读函数。

Note, you are not able to write characters using either method. However, that functionality is a bit easier to understand with the .charAt() function which, in most languages, is a read-only function.

这篇关于string.charAt(x)或string [x]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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