爲什麼stringify的輸出缺少百分號?Javascript stringify'%%'失去百分號
var a = ["dp",'%%'];
var t = JSON.stringify (a);
console.log ('t: ' + t);
結果是:
t: ["dp","%"]
爲什麼不是結果:
t: ["dp","%%"]
謝謝!
爲什麼stringify的輸出缺少百分號?Javascript stringify'%%'失去百分號
var a = ["dp",'%%'];
var t = JSON.stringify (a);
console.log ('t: ' + t);
結果是:
t: ["dp","%"]
爲什麼不是結果:
t: ["dp","%%"]
謝謝!
至於在Node.js的console.log
的文檔中指定,該函數接受一個printf-like way參數:
第一個參數是包含零個或多個佔位符的字符串。
每個佔位符都用其相應參數中的轉換值替換。支持的佔位符爲:%s - 字符串。
%d - 數字(整數和浮點數)。
%j - JSON。如果參數包含循環引用,則替換爲字符串'[Circular]'。
%% - 單個百分號('%')。這不會消耗一個參數。
如果佔位符沒有相應的參數,則不替換佔位符。
因此,印刷在一個字符串的%%
任何發生在Node.js的(未瀏覽器)console.log
將由單個%
代替。任何%s
,%d
或%j
將分別被替換爲字符串,數字或JSON字符串。下面是一些例子:
console.log("This is a string: %s", "Hello, World!");
//= This is a string: Hello, World!
console.log("This is a number: %d", 3.14);
//= This is a number: 3.14
console.log("This is a JSON string: %j", { value: true });
//= This is a JSON string: {"value":true}
console.log("This is a single percentage sign: %%");
//= This is a single percentage sign: %
console.log("If we use %%s and %%d here we get '%s' and '%d'.", "a string", 100);
//= If we use %s and %d here we get 'a string' and '100'.
在瀏覽器中調用console.log
,但是,將只打印與沒有上述置換的普通字符串。
謝謝@Frxstrem! – tgoneil
它與JSON.stringify
沒有任何關係。我只需要做console.log('%%')
就可以用node 0.10.36
重現單個%
輸出。這可能是util.format
按節點內部使用的console.log
的問題。
https://nodejs.org/docs/latest-v0.10.x/api/util.html#util_util_format_format
然而,在node 4.0
我得到預期的結果。
感謝您的提示。只需升級到節點4.2.1,現在也可以根據需要獲取%%。 – tgoneil
我不能重現這一點,我跑了你發佈的確切代碼,並得到後者的結果。 – Frxstrem
我運行它與node.js v0.10.36 – tgoneil
有趣。我剛剛與JSBin一起運行,也獲得了後者的結果。 – tgoneil