Gabriel Lang
Gabriel Lang

Reputation: 13

Javascript: How to copy an arrays value into a variable

So I am trying to get this problem solved it's a simple question but it keeps saying I'm not doing it correctly. The problem wants me to take the indexed value of the array.(In this case "batman") and copy it's value into an array. So my first thought was to use .slice() to do the job. But when I console.log() after slicing it into a variable(var thirdHero) I see that what was put into the variable was ["batman"] instead of just "batman". Any help as to how to do this problem would be so appreciated!

//#7 Create an array of strings that are the 7 primary colors in the rainbow - red, orange, yellow, green, blue, indigo, violet (lower-case). Call your array rainbowColors
var rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// #8 Using this array do the following
var heroes = ['superman', 'batman', 'flash'];
// add 'wonderwoman' to the end
heroes.push('wonderwoman');
console.log(heroes);
// remove 'superman' and store him in a variable called firstHero
var firstHero = heroes.shift();
// add 'spongebob' to the start of the array
heroes.unshift('spongebob');
// remove 'flash' from the array and store him in a variable called secondHero
var secondHero = heroes.splice(2, 1);
console.log(heroes);
// leave batman in the array but put a copy of him on a variable called thirdHero
var thirdHero = heroes.slice(1, 2);
console.log(thirdHero);

Upvotes: 0

Views: 106

Answers (1)

Dmitry Matveev
Dmitry Matveev

Reputation: 5376

you don't need to slice an array to get a reference to just a single value from it.

'slice' function returns you an array itself

just do

var hero = heroes[2];

Upvotes: 2

Related Questions