15

Is there some way I can define String[int] to avoid using String.CharAt(int)?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Jimmy
  • 89,068
  • 17
  • 119
  • 137

4 Answers4

13

No, there isn't a way to do this.

This is a common question from developers who are coming to JavaScript from another language, where operators can be defined or overridden for a certain type.

In C++, it's not entirely out of the question to overload operator* on MyType, ending up with a unique asterisk operator for operations involving objects of type MyType. The readability of this practice might still be called into question, but the language affords for it, nevertheless.

In JavaScript, this is simply not possible. You will not be able to define a method which allows you to index chars from a String using brackets.

@Lee Kowalkowski brings up a good point, namely that it is, in a way, possible to access characters using the brackets, because the brackets can be used to access members of a JavaScript Array. This would involve creating a new Array, using each of the characters of the string as its members, and then accessing the Array.

This is probably a confusing approach. Some implementations of JavaScript will provide access to a string via the brackets and some will not, so it's not standard practice. The object may be confused for a string, and as JavaScript is a loosely typed language, there is already a risk of misrepresenting a type. Defining an array solely for the purposes of using a different syntax from what the language already affords is only gong to promote this type of confusion. This gives rise to @Andrew Hedges's question: "Why fight the language?"..

There are useful patterns in JavaScript for legitimate function overloading and polymorphic inheritance. This isn't an example of either.

All semantics aside, the operators still haven't been overridden.

Side note: Developers who are accustomed to the conventions of strong type checking and classical inheritance are sometimes confused by JavaScript's C-family syntax. Under the hood, it is working in an unfamiliar way. It's best to write JavaScript in clean and unambiguous ways, in order to prevent confusion.

Nayuki
  • 17,911
  • 6
  • 53
  • 80
keparo
  • 33,450
  • 13
  • 60
  • 66
  • 1
    Not factually correct, as there is a way to avoid it. Just because it's "discouraged" doesn't mean it doesn't exist. – Lee Kowalkowski Oct 31 '08 at 22:09
  • No, you haven't actually done it. You changed the type. Developers coming to javascript from other languages are wondering if there are good conventions for overriding operators. In javascript, you simply can't "define" the brackets on a String object. It's impossible. – keparo Oct 31 '08 at 22:15
  • Oh, string in the question was lowercase, so didn't confuse that with the type. See your point. – Lee Kowalkowski Oct 31 '08 at 22:20
  • No worries. I've capitalized it to make it more clear for future readers. Ironically, that's just the type of confusion I'm referring to.. – keparo Oct 31 '08 at 23:20
11

Please note: Before anybody else would like to vote my answer down, the question I answered was:

IE javascript string indexers

is there some way I can define string[int] to avoid using string.CharAt(int)?"

Nothing about specifically overriding brackets, or syntax, or best-practice, the question just asked for "some way". (And the only other answer said "No, there isn't.")


Well, there is actually, kind of:

var newArray = oldString.split(''); 

...now you can access newArray using bracket notation, because you've just converted it to an array.

Community
  • 1
  • 1
Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46
  • @keparo: ...because? Please read ECMA-262 Section 15.5.4.14 before answering. There may be a valid reasons for converting a string to an array, e.g. sorting for anagram comparisons. – Lee Kowalkowski Oct 31 '08 at 22:15
  • Creating an array called "newString" is a confusing practice, especially in a loosely typed environment. The question is whether or not brackets can be used to access characters of a string. In another language, you can legitimately do this. In javascript, you cannot. – keparo Oct 31 '08 at 22:18
  • Oh naming convention was not supposed to be the focus in my answer, that is easily remedied (unless you're deliberately missing the point). My answer was that brackets *can* be used - by converting the string to an array. So it is possible. I thought you were saying *that* was highly discouraged. – Lee Kowalkowski Oct 31 '08 at 22:24
  • 2
    Sorry for the back and forth. My point is that you cannot define the bracket operators, in any way. That's the heart of this question. In some languages, developers are free to do this, and developers who come to javascript from another community are wondering whether it's possible. It's not. – keparo Nov 01 '08 at 00:33
2

Use String.charAt()

It's standard and works in all browsers.

In non-IE browsers you can use bracket notation to access characters like this:

"TEST"[1]; // = E

You could convert a string into an array of characters doing this:

var myString = "TEST";
var charArray = myString.split(''); // charArray[1] == E

These would be discouraged. There isn't any reason not to use the charAt() method, and there is no benefit to doing anything else.

keparo
  • 33,450
  • 13
  • 60
  • 66
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

This is not an answer, just a trick (strongly deprecated!). It shows, in particular, that in Javascript you can do whatever you want. It's just a matter of your fantasy.

You can use a fact that you can set any additional properties to String Object like to all others, so you can create String.0, String.1, ... properties:

String.prototype.toChars = function()  {
    for (var i=0; i<this.length; i++) {
        this[i+""] = this.charAt(i);
    }
};

Now you can access single characters using:

var str = "Hello World";
str.toChars();
var i = 1+"";
var c = str[i]; // "e"

Note that it's useful only for access. It should be another method defined for assigning string chars in such manner.

Also note that you must call .toChars() method every time you modify the sting.

Thevs
  • 3,189
  • 2
  • 20
  • 32
  • I'm not sure what this comment means. It works on any string as long as you call toChars on it first. It shows how to create index-accessible string, and the author clearly states it's for demonstration only. – Jacob Mouka Jun 23 '13 at 18:40