gpt4 book ai didi

javascript - 使用函数返回的值更新初始化的字符串

转载 作者:行者123 更新时间:2023-11-27 22:37:18 25 4
gpt4 key购买 nike

有没有办法更新用函数返回的值初始化的字符串?

以下是我所说内容的示例:

var level = 1,
returnLevel = function() {
return level;
},
str = 'level: ' + returnLevel();

level = 2;

// how to update the var str without doing 'level:' + level?

编辑:真实代码,因为有人问(我大大缩小了这段代码):

function returnPrice(what) {
return g.items[what].baseCost;
};

g.items = {
'item-1': {
baseCost: 100
},
'item-2': {
baseCost: 1000
},
'item-3': {
baseCost: 5000
}
};

g.console.commands = [
{
name: 'buy',
desc: 'command desc',
commands: [
{
name: 'buy item',
desc: 'buy specified item',
customDesc: [
'test desc $' + returnPrice('item-1') + '.',
'test desc $' + returnPrice('item-2') + '.',
'test desc $' + returnPrice('item-3') + '.'
]
}
]
}
];

最佳答案

另一种方法是使用 str 作为函数并实现 toString 方法来调用不带括号的实际值。

var level = 1,
returnLevel = function () {
return level;
},
str = function () {
function f() { }
f.toString = function () {
return 'level: ' + returnLevel();
}
return f;
}();

console.log(str);
level = 2;
console.log(str);

关于javascript - 使用函数返回的值更新初始化的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005708/

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