javascript - 标记的模板内部行为
问题描述
我想知道为什么会这样。f
返回一个数组,但深度检查返回true
.
const tag = (string, ...values) => string
const f = x => tag`hello ${x}`
console.log(f(1) === f(2)) //prints true
来源https://twitter.com/justinfagnani/status/1247652729922531328
解决方案
方法根据模板文字f
返回数组,并且在这两种情况下它都返回相同的数组引用。当您初始化第二个(相同的主体)模板文字时,输出会发生变化。strings
tag
const tag = (strings, ...values) => strings
const f = x => tag`hello ${x}`
const g = x => tag`hello ${x}`
console.log(f(1)) //prints [ 'hello ', '' ]
console.log(f(2)) //prints [ 'hello ', '' ]
console.log(g(1)) //prints [ 'hello ', '' ]
console.log(g(2)) //prints [ 'hello ', '' ]
console.log(f(1) === f(1)) //prints true
console.log(f(1) === g(1)) //prints false
console.log(g(2) === g(1)) //prints true
2. 每次我们第一次执行新的模板文字(初始化)时,我们都会创建一个新的数组实例,但是字符串数组保存在内存中并且文字传递了它的引用。
const x = 5
const tag = (strings, ...values) => strings
const f = tag`hello ${x}`
console.log((tag`hello ${x}`) === (tag`hello ${x}`)); //prints false
console.log(f === f); //prints true
推荐阅读
- postgresql - PostgreSQL:更改选择查询返回的所有表
- bash - 如何在 shell 中使用 $var$i
- r - 在绘图中重新定位颜色条并更改颜色比例(R)
- curl - curl TLS握手不成功
- sql - oracle中是否有与concat_ws等价的东西?
- react-native - 如何持久化 Redux 表单值?
- stm32 - STM32 Keil - 调试时无法访问目标(AT 命令 UART)
- c# - 按字母顺序组织库存
- microsoft-teams - 从 C# 在团队中创建和回复帖子
- email - 使用 curl 请求发送动态模板时 dynamic_template_data 不起作用 - Sendgrid API