我有一个这样的数组:
var array = [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
]
我收到一条错误消息,指出name
未定义,所以如果我将name = '';
放在它之前,并循环遍历数组,它就会说
Hey there, !
It's nice to see join us.
Everybody welcome !
Thanks,
有没有办法可以做类似的事情:
name = 'Albz'
console.log(array[0]);
让它回应
Hey there, Albz!
name
变量是动态的,并且会在forEach
的每次迭代中发生变化,因此无法对其进行硬编码,并且我不想每次都重新声明数组时间因为它很长。
有办法做到这一点吗?
答案 0 :(得分:4)
var nameArr = ['Ayan', 'Arnab', 'Akash'];
function process(name) {
return [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
];
}
for (var i = 0, len = nameArr.length; i < len; i += 1) {
console.log(process(nameArr[i])[0]);
}
&#13;