Skip to content
Advertisement

How to do [:] like in Python but in JavaScript?

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 🙂

Advertisement

Answer

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).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement