将另一个值分配给字符串变量

时间:2018-05-16 18:54:01

标签: javascript

抱歉,如果以前问过这个问题,我想这很简单,但我无法弄明白:我怎样才能重新分配变量的值?我需要下面代码的结果是“Hello Ana”和“Hello Maria”,但它不能识别第二个任务,我得到“Hello Ana”两次。谢谢! screenshot

var name = "Ana";
var greeting = "Hello " + name;
console.log(greeting);
name = "Maria";
console.log(greeting);

1 个答案:

答案 0 :(得分:2)

如果您希望greeting包含name变量的当前值,则必须将其更改为函数:



var name = "Ana";
var greeting = () => "Hello " + name;
console.log(greeting());
name = "Maria";
console.log(greeting());