JavaScript access string chars as array

前端 未结 4 503
日久生厌
日久生厌 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条回答
  •  萌比男神i
    2020-11-30 02:51

    Using charAt is probably the best idea since it conveys the intent of your code most accurately. Calling substr for a single character is definitely an overkill.

    alert(myString.charAt(0));
    

提交回复
热议问题