尝试理解字符串插值中的 `${c}` 如何指向数组中的元素

问题描述 投票:0回答:3
const continents = ['Africa', 'America', 'Asia', 'Australia', 'Europe'];

const helloContinents = Array.from(continents, c => `Hello ${c}!`);

const message = helloContinents.join(' ');

const element = React.createElement("div", {

  title: "Outer div"

}, React.createElement("h1", null, message));

ReactDOM.render(element, document.getElementById('contents'));
javascript arrays reactjs arrow-functions string-interpolation
3个回答
1
投票

来自

Array.from

的文档

参数

arrayLike 要转换为数组的类数组或可迭代对象。

mapFn 可选的 Map 函数,用于调用数组的每个元素。

thisArg 执行mapFn时用作this的可选值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Syntax

它表示第二个参数是映射函数,它适用于数组中的每个元素。


0
投票

这个字符串插值中的

${c}
如何指向数组中的元素

事实并非如此。

c => `Hello ${c}!`
是一个箭头函数,一次获取一个参数 (
c
)。
如果你想支持没有字符串插值的环境,你可以写
c => "Hello "+c+"!"
,可以将其膨胀为
c => {return "Hello "+c+"!";}
,以强调它是一个非常紧凑但实际的功能。
10 年前,如果没有插值和箭头函数,您可能会写出
function(c){return "Hello "+c+"!";}
在那里。

因此,正如其他答案/评论指出的那样,使用

Array.from(someIterable,someFunction)
只需在
someFunction
的所有元素上调用
someIterable
,将结果收集到数组中。然后
join()
将数组元素连接成单个字符串。由于您的“可迭代”已经是一个数组,因此您可以使用
Array.map(someFunction)
代替。

一些变化,还添加了日志记录,提供长

function(x)

const continents = ['Africa', 'America', 'Asia', 'Australia', 'Europe'];
const hellos1 = Array.from(continents,function(x){
  console.log("processing element: "+x);
  return "Hello "+x+"!";
});
console.log(hellos1.join(" "));

const hellos2 = continents.map(x => {return "Hello "+x+"!"});
console.log(hellos2.join()); // comma-separated

console.log(`1+2: ${1+2}, continents.length: ${continents.length}`);

最后一行显示字符串插值中的

${...}
只是简单地计算里面的表达式。因此,问题中
c
${c}
不是格式说明符,就像
\c
可以采用多种语言一样,它是
c
只是因为这是箭头函数获取的参数名称。


0
投票

只需记住在 ${c} 周围的 mapFn 的原始语法中使用反引号 (`) 与单引号 (') 相反

const helloContinents = Array.from(大陆, c =>

Hello ${c}!
);

即当后面的勾号内的内容被作为函数求值时。

© www.soinside.com 2019 - 2024. All rights reserved.