作为我学习练习的一部分,我正在尝试使用For循环创建一个函数。该函数返回一个新的数组变量merges并匹配数组Y = eye(num_labels)(y, :);
和musicians
的索引值。
所以预期的回报应该是字符串:
“约翰·列侬演奏吉他”
这是我的尝试,但我一直没有得到回报:
instruments
答案 0 :(得分:1)
您在循环的每次迭代中都会覆盖变量。您需要创建一个空数组并填充它(然后返回它):
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));
答案 1 :(得分:1)
存在一些问题。
该函数需要返回合并的数组。 其次,函数从未被调用过。您可能不需要再次在循环中创建变量
var musicians = ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"]
var instruments = ["Guitar", "Bass Guitar", "Lead Guitar", "Drums"]
function theBeatlesPlay(musicians, instruments) {
var mergedArray = [];
for (let i = 0; i < musicians.length; i++) {
mergedArray.push(musicians[i] + " plays " + instruments[i])
}
return mergedArray;
}
console.log(theBeatlesPlay(musicians, instruments))
答案 2 :(得分:0)
根据您的代码进行的观察很少:
;
,以获得良好的编码实践。console.log
语句放在for
循环中,因为它会在for循环中打印迭代值。newMusicians[i]
在console.log中使用newMusicians
。
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 + " plays " + instruments[i]);
}
}
theBeatlesPlay(musicians, instruments);
答案 3 :(得分:-1)
您需要将console.log
放入for
循环中。
此外,console.log(newMusicians + " plays " + instruments[i])
newMusicians
而不是newMusicians[i]
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 + " plays " + instruments[i])
}
}
theBeatlesPlay(musicians, instruments);