gpt4 book ai didi

javascript for 循环函数合并两个新数组。

转载 作者:行者123 更新时间:2023-12-03 04:15:11 24 4
gpt4 key购买 nike

作为学习练习的一部分,我正在尝试创建一个带有 For 循环的函数。该函数返回一个新的数组变量,合并并匹配数组 musiciansinstruments 的索引值。所以预期的返回应该是字符串:“约翰·列侬弹吉他”

这是我的尝试,但我一直未能获得返回:

var musicians = ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"]
var instruments = ["Guitar", "Bass Guitar", "Lead Guitar", "Drums"]

function theBeatlesPlay(musicians, instruments) {

for (let i=0; i<musicians.length; i++) {

var newMusicians = musicians[i]
var newInstruments = instruments[i]
}

console.log(newMusicians[i] + "plays" + instruments[i])
}

最佳答案

您将在循环的每次迭代中覆盖变量。您需要创建一个空数组并填充它(然后返回它):

var musicians = ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"]
var instruments = ["Guitar", "Bass Guitar", "Lead Guitar", "Drums"]

function theBeatlesPlay(musicians, instruments) {
var combinations = [];

for (let i = 0; i < musicians.length; i++) {
combinations.push(musicians[i] + ' plays ' + instruments[i]);
}

return combinations;
}

console.log(theBeatlesPlay(musicians, instruments));

关于javascript for 循环函数合并两个新数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44172767/

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