将变量传递给数组中间字符串

时间:2016-07-26 14:08:28

标签: javascript arrays variables scope

我有一个这样的数组:

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的每次迭代中发生变化,因此无法对其进行硬编码,并且我不想每次都重新声明数组时间因为它很长。

有办法做到这一点吗?

1 个答案:

答案 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;
&#13;
&#13;