Reputation: 19
What do curly brackets ({}
) do in variable declarations, when surrounding multiple pairs of the form integer:string
?
For example, what do they mean here?
char = {0:'(',3:') ',6:' - '};
In this case, it's from the following phone number formatting script:
function formatPhone(obj) {
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
for (var i = 0; i < numbers.length; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
I believe that the line defining char
is the one that's causing it to fail.
Upvotes: 1
Views: 1896
Reputation:
This is a Javascript object. Better indented, it would look like this:
char = {
0: '(',
3: ') ',
6: ' - '
}
It's saying that you're making an object with properties 0
, 3
, and 6
set to the given values. Then, the properties are accessed with char[i]
, which returns null
unless the property is defined -- so for all i
except 0, 3, and 6, it'll default to ''
. For 0, 3, and 6, it'll take the relevant strings.
Alright, I think I figured out what's 'not working', though again I'd need you to explain what that means before I can be sure.
This line:
obj.value += (char[i]||'') + numbers[i];
will insert undefined
in the string if numbers[i]
isn't defined, and numbers[i]
is only defined for i
= 0, 3, or 6. Change the line to this:
obj.value += (char[i]||'') + (numbers[i]||'');
and it should work.
Upvotes: 3
Reputation: 124
That is a Javascript object.
In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.
The syntax for an object using an object initializer is:
var obj = { property_1: value_1, // property_# may be an identifier... 2: value_2, // or a number... // ..., "property n": value_n }; // or a string
where obj is the name of the new object, each
property_i
is an identifier (either a name, a number, or a string literal), and eachvalue_i
is an expression whose value is assigned to theproperty_i
.
The rest of this article is available here.
Upvotes: 1
Reputation: 2486
It creates an object:
obj = {0:'(',3:') ',6:' - '};
You have two elements inside your object with keys 0, 3 and 6. You can access them obj[0], obj[3] and obj[6]
Or you can access them in a loop as you did in your example
Upvotes: 1