0

I want to access data of var a so it is: 245 but instead it only accesses the last one. so if i print it out it says 5

var A = [1, 2, 3, 4, 5];
var B = A[[1], [3], [4]];
console.log(B)

Tibebes. M
7,6285 gold badges19 silver badges40 bronze badges
asked Oct 24, 2020 at 18:42

5 Answers 5

1

When accessing an object using square bracket notation — object[expression] — the expression resolves to the string name of the property.

The expression [1], [3], [4] consists of three array literals separated by comma operators. So it becomes [4]. Then it gets converted to a string: "4". Hence your result.

JavaScript doesn't have any syntax for picking non-contiguous members of an array in a single operation. (For contiguous members you have the slice method.)

You need to get the values one by one.

var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B.join(""))

answered Oct 24, 2020 at 18:47
Sign up to request clarification or add additional context in comments.

Comments

0

var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B)

answered Oct 24, 2020 at 18:46

1 Comment

i tried this but i didn't put bracket notation before the first one so it was A[[1], A[3], [4]] I shouldve thought about that
0

You'll need to access A multiple times for each index.

var A = [1, 2, 3, 4, 5];
var B = A[1];
console.log(A[1], A[3], A[4])

answered Oct 24, 2020 at 18:47

Comments

0

You can access them directly like that. If you want to access index 2 for example, you should do console.log(A[1]); You can't access multiple indices at the same time. A variable can have only one value.

answered Oct 24, 2020 at 18:47

Comments

0

@Quentin solution resolve the problem, I wrote this solution to recommend you to create an array of index, and iterate over it.

Note: You are getting the last index, because you are using the comma operator. The comma operator allows you to put multiple expressions. The resulting will be the value of the last comma separated expression.

const A = [1, 2, 3, 4, 5];
const indexes = [1,3,4];
const B = indexes.map(i => A[i]).join``;
console.log(B);

answered Oct 24, 2020 at 20:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.