Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

JavaScript access string chars as array

Is it ok to do this:

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

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.

Thank you.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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:

var myString = "Hello!";
var strChars = myString.split("");
alert(strChars[0]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...