Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - string.charAt(x)或string [x]?(string.charAt(x) or string[x]?)

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

  ask by Blender translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bracket notation now works on all major browsers, except for IE7 and below.

(括号表示法现在适用于所有主流浏览器,IE7及更低版本除外。)

// Bracket Notation
"Test String1"[6]

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

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

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

This notation does not work in IE7.

(这种表示法在IE7中不起作用。)

The first code snippet will return undefined in IE7.

(第一个代码片段将在IE7中返回undefined。)

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.

(如果您使用的是.charAt(pos)函数,那么您就不会想要这样做。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...