Is there some way I can define String[int] to avoid using String.CharAt(int)?
Is there some way I can define String[int] to avoid using String.CharAt(int) ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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*onMyType, ending up with a unique asterisk operator for operations involving objects of typeMyType. 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
Stringusing 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 newArray, using each of the characters of the string as its members, and then accessing theArray.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.