So I was just writing some code and realized that adding square brackets around an array just returns a complete, normal array like below,
var arr = [1, 2, 3]
var addSquareBrackets = function(arr) {
return '[' + arr + ']';
}
addSquareBrackets(arr); // <- returns [1, 2, 3]
and same thing happens when concatenating curly brackets around an array.
var arr = [1, 2, 3]
var addCurlyBrackets = function(arr) {
return '{' + arr + '}';
}
addCurlyBrackets(arr); // <- returns {1, 2, 3}
It seems odd to me how the first example returns [1, 2, 3], instead of [[1, 2, 3]] or the second example returns {1, 2, 3}, instead of {[1, 2, 3]}. Can someone help me understand why this happens?
With the +
operator, whenever you have a string on one side, whatever expression on the other side gets coerced into a string as well.
Arrays, when coerced to strings, have .join(',')
called on them:
console.log(String([1, 2, 3]));
They do not get [
]
array delimiters added around the result - they just get the plain values joined together by commas.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.