-1

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

5
  • 1
    if a[:] does a shallow copy of a, then the equivalent would be [...a] Commented Dec 25, 2021 at 6:57
  • what if I wanted to do a[:1] to get only ["one", "two"]? @RameshReddy Commented Dec 25, 2021 at 7:09
  • 3
    Does this answer your question? JavaScript take part of an array Commented Dec 25, 2021 at 7:27
  • Don't ask "how can I do the equivalent of <language X code> in language Y?", unless that is the only way you can describe the problem. It is much better to ask directly how to do the thing that you want the code to do - in this case, either copy (if you specifically mean [:]) or slice (the general concept) the Javascript array. And having figured this out, you are well on your way to using a search engine to find an answer. Commented Dec 25, 2021 at 7:49
  • Please also only tag languages that are relevant to the problem itself, not to how you have decided to describe the problem. Just as you wouldn't tag your IDE unless you were asking a question about how to use the IDE. A question should only have multiple language tags if you must write code in each tagged language in order to solve the problem and that code must interoperate (if the pieces of code stand on their own, then you have separate questions about each). Commented Dec 25, 2021 at 7:51

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The solution is by using the slice method. I played around with it until I eventually understand how it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.