Marco Rispoli
Marco Rispoli

Reputation: 65

how can i do this with js?

Hello this is my problem. I should make this code [1,4,6,3,4,6].repeat() return me as output this [1,4,6,3,4,6,1,4,6,3,4,6]. I didn't understand how to set the resolution though. Can you help me ?

Upvotes: 0

Views: 72

Answers (3)

Hao Asakura
Hao Asakura

Reputation: 1

This probably can help you with your problem. It let you define your own function for array.

Array.prototype.repeat= function(){
  return this.concat(this);
}

[1,4,6,3,4,6].repeat();

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

This should do it:

Array.prototype.repeat = function() {
  return [...this, ...this];
}

console.log([1,4,6,3,4,6].repeat())

Note that changing the prototype of built-in types is generally not a good idea, and can lead to unexpected behavior.

Upvotes: 3

Justinas
Justinas

Reputation: 43481

Use .concat on same array:

var myArray = [1,4,6,3,4,6];
var newArray = myArray.concat(myArray);
console.log(newArray)

Upvotes: 3

Related Questions