JavaScript中如何调用一次函数并在数组值中重复使用其返回值?
解决同一模板字符串中复用随机数的几种JS方案
嘿,这个问题我之前也碰到过!你已经知道把随机数存到变量里是最直接的解法,但确实还有几种JavaScript的技巧能帮你在不提前声明变量的情况下实现需求,我给你列几个实用的方案:
1. 闭包生成“固定值”随机数生成器
用闭包封装一个只会生成一次随机数的函数,后续调用都返回同一个缓存值:
"use strict"; // 创建一个闭包函数,返回的内部函数会缓存随机数 function getFixedRandom() { let cachedRandom; return () => { if (!cachedRandom) { cachedRandom = Math.random() * 10; } return cachedRandom; }; } // 实例化这个固定随机数生成器 const fixedRandom = getFixedRandom(); let myArray = [ `Use a random number once here, ${fixedRandom()}, and the same value again here ${fixedRandom()}.` ]; document.querySelector('.output').textContent = myArray[0];
这个方案的好处是,如果你需要在多个地方复用同一个随机数,只需要调用fixedRandom()就行,不用重复写逻辑。
2. 自定义标签模板字符串
利用ES6的标签模板功能,自定义一个标签函数来统一处理模板里的随机数复用:
"use strict"; // 自定义标签函数:给所有占位符分配同一个随机数 function reuseRandom(strings) { const randomNum = Math.random() * 10; // 拼接模板字符串和随机数 return strings.reduce((result, str, index) => { if (index === 0) return str; return result + randomNum + str; }); } // 使用标签模板,占位符位置留空即可 let myArray = [ reuseRandom`Use a random number once here, ${}, and the same value again here ${}.` ]; document.querySelector('.output').textContent = myArray[0];
这种方式适合你需要在同一个模板里多次复用同一个动态值的场景,扩展性也不错——如果以后要改成复用其他值,只需要修改标签函数里的逻辑就行。
3. 立即执行函数表达式(IIFE)
在模板字符串里嵌入一个IIFE,直接在内部生成随机数并返回拼接好的字符串:
"use strict"; let myArray = [ `${(() => { const num = Math.random() * 10; return `Use a random number once here, ${num}, and the same value again here ${num}.`; })()}` ]; document.querySelector('.output').textContent = myArray[0];
这个方案比较“轻量”,适合只在单个模板里复用一次随机数的场景,缺点是可读性不如前两种,逻辑太紧凑。
最后补充一句
虽然上面这些方法都能解决问题,但把随机数提前存在变量里其实是可读性最高、最容易维护的方案,除非你有特殊场景必须避免提前声明变量,否则我还是优先推荐这种最直观的写法:
"use strict"; const randomNum = randomNumber(); let myArray = [ `Use a random number once here, ${randomNum}, and the same value again here ${randomNum}.` ]; function randomNumber() { return Math.random() * 10; } document.querySelector('.output').textContent = myArray[0];
内容的提问来源于stack exchange,提问作者DR01D
相关产品推荐
相关产品推荐

