Why does [1,2] + [3,4] =
Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
I wanted to add the elements of an array into another, so I tried this simple sentence in our beloved Firebug:
[1,2] + [3,4]
It responded with:
"1,23,4"
What is going on?
Answer by Doug for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
It adds the two arrays as if they were strings.
The string representation for the first array would be "1,2" and the second would be "3,4". So when the +
sign is found, it cannot sum arrays and then concatenate them as being strings.
Answer by Jamie Dixon for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
It's doing exactly what you asked it to do.
What you're adding together are array references (which JS converts to strings), not numbers as it seems. It's a bit like adding strings together: "hello " + "world"
= "hello world"
Answer by Saul for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
The +
operator is not defined for arrays.
What happens is that Javascript converts arrays into strings and concatenates those.
Update
Since this question and consequently my answer is getting a lot of attention I felt it would be useful and relevant to have an overview about how the +
operator behaves in general also.
So, here it goes.
Excluding E4X and implementation-specific stuff, Javascript (as of ES5) has 6 built-in data types:
- Undefined
- Null
- Boolean
- Number
- String
- Object
Note that although typeof
somewhat confusingly returns object
for Null and function
for callable Objects, Null is actually not an Object and strictly speaking, in specification-conforming Javascript implementations all functions are considered to be Objects.
That's right - Javascript has no primitive arrays as such; only instances of an Object called Array
with some syntactic sugar to ease the pain.
Adding more to the confusion, wrapper entities such as new Number(5)
, new Boolean(true)
and new String("abc")
are all of object
type, not numbers, booleans or strings as one might expect. Nevertheless for arithmetic operators Number
and Boolean
behave as numbers.
Easy, huh? With all that out of the way, we can move on to the overview itself.
Different result types of +
by operand types
|| undefined | null | boolean | number | string | object | ========================================================================= undefined || number | number | number | number | string | string | null || number | number | number | number | string | string | boolean || number | number | number | number | string | string | number || number | number | number | number | string | string | string || string | string | string | string | string | string | object || string | string | string | string | string | string |
* applies to Chrome13, FF6, Opera11 and IE9. Checking other browsers and versions is left as an exercise for the reader.
Note: As pointed out by CMS, for certain cases of objects such as Number
, Boolean
and custom ones the +
operator doesn't necessarily produce a string result. It can vary depending on the implementation of object to primitive conversion. For example var o = { valueOf:function () { return 4; } };
evaluating o + 2;
produces 6
, a number
, evaluating o + '2'
produces '42'
, a string
.
To see how the overview table was generated visit http://jsfiddle.net/1obxuc7m/
Answer by Adam Fabicki for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
It looks like JavaScript is turning your arrays into strings and joining them together. If you want to add tuples together, you'll have to use a loop or a map function.
Answer by tadman for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
It's converting the individual arrays to strings, then combining the strings.
Answer by Jeremy Banks for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
JavaScript's +
operator has two purposes: adding two numbers, or joining two strings. It doesn't have a specific behaviour for arrays, so it's converting them to strings and then joining them.
If you want to join two arrays to produce a new one, use the .concat
method instead:
[1, 2].concat([3, 4]) // [1, 2, 3, 4]
If you want to efficiently add all elements from one array to another, you need to use the .push method in this somewhat-verbose way:
var data = [1, 2]; Array.prototype.push.apply(data, [3, 4]); // data is now [1, 2, 3, 4]
The behaviour of the +
operator is defined in ECMA-262 5e Section 11.6.1:
11.6.1 The Addition operator ( + )
The addition operator either performs string concatenation or numeric addition. The production
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingAdditiveExpression
.- Let
lval
beGetValue(lref)
.- Let
rref
be the result of evaluatingMultiplicativeExpression
.- Let
rval
beGetValue(rref)
.- Let
lprim
beToPrimitive(lval)
.- Let
rprim
beToPrimitive(rval)
.- If
Type(lprim)
isString
orType(rprim)
isString
, then
- Return the String that is the result of concatenating
ToString(lprim)
followed byToString(rprim)
- Return the result of applying the addition operation to
ToNumber(lprim)
andToNumber(rprim)
. See the Note below 11.6.3.
You can see that each operand is converted ToPrimitive
. By reading further we can find that ToPrimitive
will always convert arrays to strings, producing this result.
Answer by Rocket Hazmat for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
The +
concats strings, so it converts the arrays to strings.
[1,2] + [3,4] '1,2' + '3,4' 1,23,4
To combine arrays, use concat
.
[1,2].concat([3,4]) [1,2,3,4]
Answer by maerics for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
In JavaScript, the binary addition operator (+
) performs both numerical addition and string concatenation. However, when it's first argument is neither a number nor a string then it converts it into a string (hence "1,2
") then it does the same with the second "3,4
" and concatenates them to "1,23,4
".
Try using the "concat" method of Arrays instead:
var a = [1, 2]; var b = [3, 4]; a.concat(b) ; // => [1, 2, 3, 4];
Answer by user286806 for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
[1,2]+[3,4]
in JavaScript is same as evaluating:
new Array( [1,2] ).toString() + new Array( [3,4] ).toString();
and so to solve your problem, best thing would be to add two arrays in-place or without creating a new array:
var a=[1,2]; var b=[3,4]; a.push.apply(a, b);
Answer by Prashant Singh for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
It is because, + operator assumes that the operands are string, if they are not numbers. So, it first converts them to string and concats to give the final result , if its not a number. Also, it does not support arrays.
Answer by George Birbilis for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
would be nice if you could overload operators in JavaScript but you can't: Can I define custom operator overloads in Javascript? you can only hack the "==" operator which converts to strings before comparing: http://blogger.xs4all.nl/peterned/archive/2009/04/01/462517.aspx
Answer by Blackhead for Why does [1,2] + [3,4] = "1,23,4" in JavaScript?
Another result using just a simple "+" sign will be:
[1,2]+','+[3,4] === [1,2,3,4]
So something like this should work (but!):
var a=[1,2]; var b=[3,4]; a=a+','+b; // [1,2,3,4]
... but it will convert the variable a from an Array to String! Keep it in mind.
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment