gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:07:56 24 4
gpt4 key购买 nike

所以我试图解决这个问题,这是一个简单的问题,但它一直说我做得不正确。问题希望我获取数组的索引值(在本例中为“ bat 侠”)并将其值复制到数组中。所以我的第一个想法是使用 .slice() 来完成这项工作。但是当我 console.log() 将其切片到变量(varthirdHero)后,我看到放入变量的是 ["batman"] 而不仅仅是“ bat 侠”。任何有关如何解决此问题的帮助将不胜感激!

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

最佳答案

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

“slice”函数返回一个数组本身

就这么做

var hero = heroes[2];

关于Javascript:如何将数组值复制到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com