JavaScript access string chars as array

前端 未结 4 520
日久生厌
日久生厌 2020-11-30 02:34

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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 03:04

    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]);
    

提交回复
热议问题