第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

推遲執(zhí)行ES6模板文字

推遲執(zhí)行ES6模板文字

繁華開滿天機 2019-10-10 16:14:24
我正在使用新的ES6模板文字功能,想到的第一件事是String.formatJavaScript,因此我著手實現(xiàn)了一個原型:String.prototype.format = function() {  var self = this;  arguments.forEach(function(val,idx) {    self["p"+idx] = val;  });  return this.toString();};console.log(`Hello, ${p0}. This is a ${p1}`.format("world", "test"));ES6提琴但是,在將模板文字傳遞給我的原型方法之前,需要先對其進行評估。有什么方法可以編寫上述代碼以將結果推遲到動態(tài)創(chuàng)建元素之后?
查看完整描述

3 回答

?
守著一只汪

TA貢獻1872條經(jīng)驗 獲得超4個贊

我可以看到三種解決方法:


使用模板字符串,就像設計使用的那樣,沒有任何format功能:


console.log(`Hello, ${"world"}. This is a ${"test"}`);

// might make more sense with variables:

var p0 = "world", p1 = "test";

console.log(`Hello, ${p0}. This is a ${p1}`);

// or even function parameters for actual deferral of the evaluation:

const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;

console.log(welcome("world", "test"));

不要使用模板字符串,而應使用純文本字符串:


String.prototype.format = function() {

    var args = arguments;

    return this.replace(/\$\{p(\d)\}/g, function(match, id) {

        return args[id];

    });

};

console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));

使用帶標簽的模板文字。請注意,替換仍將在不被處理程序攔截的情況下進行求值,因此您不能像p0沒有變量so 那樣使用標識符。如果接受其他替換主體語法建議,此行為可能會更改(更新:否)。


function formatter(literals, ...substitutions) {

    return {

        format: function() {

            var out = [];

            for(var i=0, k=0; i < literals.length; i++) {

                out[k++] = literals[i];

                out[k++] = arguments[substitutions[i]];

            }

            out[k] = literals[i];

            return out.join("");

        }

    };

}

console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));

// Notice the number literals: ^               ^


查看完整回答
反對 回復 2019-10-10
?
catspeake

TA貢獻1111條經(jīng)驗 獲得超0個贊

AFAIS,有用的功能“延遲執(zhí)行字符串模板”仍然不可用。但是,使用lambda是一種表達力強,易讀且簡短的解決方案:


var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;


console.log( greetingTmpl("world","test") );

console.log( greetingTmpl("@CodingIntrigue","try") );


查看完整回答
反對 回復 2019-10-10
  • 3 回答
  • 0 關注
  • 275 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號