Javascript:如何将数组值复制到变量中

时间:2017-01-16 00:34:18

标签: javascript arrays slice

所以我试图解决这个问题这是一个简单的问题,但它一直在说我做得不对。问题是我需要获取数组的索引值(在本例中为“batman”)并将其值复制到数组中。所以我的第一个想法是使用.slice()来完成这项工作。但是当我将console.log()切成变量(var thirdHero)后,我发现变量中的内容是["batman"],而不仅仅是"batman"。如何解决这个问题的任何帮助将非常感激!

//#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);

1 个答案:

答案 0 :(得分:2)

您不需要对数组进行切片以获取对其中单个值的引用。

'切片'函数返回一个数组本身

只是做

var hero = heroes[2];