2

次のコードを検討してください。

function f() {
  console.log(Array.from(arguments));
}

var x = 2;
var y = 3;
f`before ${x} ${y} after`;

の引数は次のようにfなります ( Traceur によると):

["before ", " ", " after"], 2, 3

すべてのリテラル文字列を置換値で連結したいとしましょう。
正しい順序でそれを行うにはどうすればよいですか?

最初の配列の「分割点」を最初の後の各引数と一致させる必要がありますか?

4

2 に答える 2

2

Draft ECMAScript 6 Specification の wiki によると、テンプレートはエスケープ シーケンスを考慮しているため、より複雑です。

テンプレート

quasiTag`literalPortion\0 $x literalPortion1`

脱糖します

// Declaration hoisted to top of module.
// Escape sequences in the hoisted declaration are not decoded according to CV(EscapeSequence).
// The calls to Object.freeze use the original definition of that method.
const unguessableCallSiteId1234 = Object.freeze({
  raw: Object.freeze(["literalPortion\\0 ", "literalPortion1"]),
  cooked: Object.freeze(["literalPortion\u0000 ", "literalPortion1"])
});

...

  // In-situ
  // Escape sequences in the arguments are decoded.
  // unguessableCallSiteId1234 is ideal as a key into a weak map used to memoize
  // extraction of meta-data, custom escaping conventions, and other state
  // that can be derived from the literal portions, so does not vary from
  // call to call from the same call-site.
  quasiTag(unguessableCallSiteId1234, x)

EcmaScript準リテラル - 脱糖

traceurargumentsで見られるように、置換値を含める必要がありますが、リテラル部分はオブジェクトであり、配列ではありません。

traceur でコンパイルされたコードに実装したい場合は、次の最適化されていない例のようにすることができます。

let concatenated = "";
Array.forEach(args[0], (e, i) =>
    concatenated += e + ( i < arguments.length - 1 ? arguments[i+1] : "")
);

実際の ECMAScript 6 コードについては、bergi がコメントで提案したように、 Default Quasi Tagの実装をご覧ください。

于 2014-07-21T15:16:19.950 に答える
2

置換よりもリテラル部分が常に 1 つ多くあります。最初のリテラルはテンプレートの最初の部分 (置換で始まる場合は空の文字列) であり、最後のリテラルはテンプレート文字列の末尾 (置換で終わる場合は空の文字列) です。

部品を順番に取得するにはliteral[0]、 、sub[0]literal[1]、 ...、 、sub[sub.length-1]にアクセスしますliteral[sub.length]

簡単な出発点は次のとおりです。

function simpleTag(lit, ...sub) {
  return sub.reduce(
    // Add next substition and following literal
    (soFar, s, i) => soFar + s + lit[i+1],
    lit[0] // Start with the first literal
  );
}
于 2016-05-06T15:15:58.137 に答える