简体   繁体   中英

Javascript construct in concatenating strings

Below a simple piece of javascript is displayed:

var mystring = ("random","ignored","text","h") + ("ello world")

This string results in hello world. I have two questions:

  • how is the ("random","ignored","text","h") construct called (its not an array, because an array has different kind of brackets?)
  • Can someone technically explain why this string results in hello world? (ie why is only the "h" character in the construct taken into account?)

You're running into the little-known comma operator !

The parentheses and comma operator create a group of expressions that are evaluated in order, then return the last one. So ('foo', 'bar') will evaluate to just 'bar' . However, because each expression is evaluated, (foo(), bar()) will call both foo() and bar() before returning the value returned by bar() .

Step by step, your code runs as:

var mystring = ("random","ignored","text","h") + ("ello world")
var mystring = "h" + ("ello world")
var mystring = "h" + "ello world"
var mystring = "hello world"

Many (or even most) languages have this operator, but it's rarely used. It can be helpful when using ES6 lambdas as the body of a reduce , like when you're turning an array into an object:

[{key: 'a', value: 1}, {key: 'b', value: 2}].reduce((p, c) => (p[c.key] = c.value, p), {})

I wouldn't necessarily suggest you use it often, since it can be confusing and there's often a more clear (if more verbose) way to do the same thing.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM