我创建了一个生成器函数。
function* ask() {
const name = yield "What is your Name.?";
const sport = yield "What is your favorite sports.?";
return `${name}'s favorite sport is ${sport}`;
}
const it = ask();
console.log(it.next());
console.log(it.next("Ng Sharma"));
console.log(it.next("Cricket"));
此代码在Node.js中运行。
{ value: 'What is your Name.?', done: false }
{ value: 'What is your favorite sports.?', done: false }
{ value: 'Ng Sharma\'s favorite sport is Cricket', done: true }
此代码在Google chorme中运行。
{value: "What is your Name.?", done: false}
{value: "What is your favorite sports.?", done: false}
{value: "Ng Sharma's favorite sport is Cricket", done: true}
为什么我要在这些'\'斜杠上加上这些多余的斜杠,以及如何摆脱它们呢?
答案 0 :(得分:0)
为什么我要在这些'\'斜杠上加上这些多余的斜杠,以及如何摆脱它们呢?
由于要输出完整的结果对象,因此将获得Node的默认对象表示形式,该表示形式在字符串周围使用单引号。由于它在字符串周围使用单引号,因此该字符串中的单引号(单引号)用反斜杠进行转义,以表示它们不是字符串的结尾(就像编写字符串时一样)用单引号引起来)。反斜杠实际上不在字符串中。 Chrome在字符串值的周围使用双引号而不是单引号,因此不需要转义'
。
如果仅输出value
,它将打印字符串内容,而不是从生成器中打印出完整的结果对象:
function* ask() {
const name = yield "What is your Name.?";
const sport = yield "What is your favorite sports.?";
return `${name}'s favorite sport is ${sport}`;
}
const it = ask();
console.log(it.next().value);
console.log(it.next("Ng Sharma").value);
console.log(it.next("Cricket").value);
输出:
What is your Name.? What is your favorite sports.? Ng Sharma's favorite sport is Cricket