Home > front end >  How to do [:] like in Python but in JavaScript?
How to do [:] like in Python but in JavaScript?

Time:12-25

in Python, you can get a list like this (array in JavaScript)

a = ["one", "two", "three"]
print(a[:]) # ["one", "two", "three"]

I'm wondering how I can do this too but in JavaScript. If it is possible, please tell me :)

CodePudding user response:

In python, a[:] creates a shallow copy of the array. The equivalent in JS is [...a].

If you just want to get the first two elements, you can use a.slice(0, 2) which returns a new array. The slice method goes from the starting index (inclusive) to the ending index (non-inclusive).

  • Related