迟到了,但是,TBH,没有一个答案能解释 50% 的原始问题(“为什么raw: Array[1]”)
1。为什么可以使用反引号调用不带括号的函数?
console.log`1`
正如其他人所指出的,这被称为Tagged Template(更多详细信息还有here)。
使用此语法,函数将接收以下参数:
- 第一个参数:一个数组,包含字符串中不是表达式的不同部分。
- 其余参数:被插值的每个值(即表达式)。
基本上,以下是“几乎”等价的:
// Tagged Template
fn`My uncle ${uncleName} is ${uncleAge} years old!`
// function call
fn(["My uncle ", " is ", " years old!"], uncleName, uncleAge);
(请参阅第 2 点。了解为什么它们不完全相同)
2。为什么["1", raw: Array[1]] ???
作为第一个参数传递的数组包含一个属性raw,它允许输入accessing the raw strings(不处理转义序列)。
示例用例:
let fileName = "asdf";
fn`In the folder C:\Documents\Foo, create a new file ${fileName}`
function fn(a, ...rest) {
console.log(a); //In the folder C:DocumentsFoo, create a new file
console.log(a.raw); //In the folder C:\Documents\Foo, create a new file
}
什么,一个有属性的数组??? ???
是的,因为 JavaScript 数组实际上是对象,所以它们可以store properties。
例子:
const arr = [1, 2, 3];
arr.property = "value";
console.log(arr); //[1, 2, 3, property: "value"]