[removed] Have we always been able to index into a string like it's an array?

前端 未结 3 728
余生分开走
余生分开走 2021-01-23 21:44

I\'ve always thought that if you want to access the nth character in a string called str, then you have to do something like str.charAt(n). Today I was

相关标签:
3条回答
  • 2021-01-23 22:11

    As long as I can remember, but:

    Array-like character access [...] is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

    (...and not supported in all browsers) See here.

    0 讨论(0)
  • 2021-01-23 22:13

    No, that was not always possible.

    If you run your code in an old enough browser, IE 7 for example, it won't be able to access the string like that. On those older engines, you'd have to use .charAt(index) instead.

    0 讨论(0)
  • 2021-01-23 22:15

    There are two ways to access an individual character in a string. The first is the charAt method:

    return 'cat'.charAt(1); // returns "a"
    

    The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:

    return 'cat'[1]; // returns "a"
    

    Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String

    0 讨论(0)
提交回复
热议问题