首页 > 解决方案 > 标记的模板内部行为

问题描述

我想知道为什么会这样。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

标签: javascript

解决方案


方法根据模板文字f返回数组,并且在这两种情况下它都返回相同的数组引用。当您初始化第二个(相同的主体)模板文字时,输出会发生变化。stringstag

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

推荐阅读