views:

1312

answers:

5

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

+5  A: 

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' 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.

Sidenote: 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.

keparo
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
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
Oh, string in the question was lowercase, so didn't confuse that with the type. See your point.
Lee Kowalkowski
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
+4  A: 

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.

Lee Kowalkowski
haha, clever... in a way I'll probably never use :)
Jimmy
This would be highly discouraged..
keparo
@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
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
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
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
+1  A: 
CMS
+1  A: 

What's the purpose of the question? Is it to find a way to access substrings that is more efficient than String.charAt? The built-in method is likely to be the most performant way to do this. Why fight the language?

Andrew Hedges
Jimmy had mentioned that he's coming from C and is accustomed to the bracket notation.
keparo
A: 

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