Kaspar Lee
Kaspar Lee

Reputation: 5596

Use Ruby's << concatenation operator in Javascript

Ruby has the << concatenation operator. It can be used to push an item to an array (.push() can also be used in Ruby, but it is longer). It is used like this:

array = [1, 2]
array << 3
return array    # Will return [1, 2, 3]

Is there a similar Javascript operator to do that, or do I have to use .push()?


Solved: There is no Javascript operator similar to <<. You have to use push (Or create a function with a short name like a and push the only argument it takes)


Upvotes: 0

Views: 56

Answers (2)

NMunro
NMunro

Reputation: 910

This is the shortest way I can think of that doesn't use push()

var arr = [1, 2, 3];
arr[arr.length] = 4;

It's also open to being wrong if the length property of arr has been externally manipulated.

arr.length = 100;

For instance. I like the best way would be to use push() but this is an alternative if you'd really like to use it. I'm not sure that a shorter way to push to arrays exists in JS.

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

JavaScript does not support operator overloading and it is language with syntax characteristics quite different from Ruby.

For instance, in Ruby, you can omit parenthesis around parameters while making a function call.

arr << 4

is equivalent to

arr.<<(4)

JavaScript does not allow such flexibility, and hence, what you are asking may not be possible

Upvotes: 3

Related Questions