我个人讨厌人们在 JavaScript 的原生类型上塞进自己的垃圾。如果我要写它,我会做以下事情......但是为什么不喜欢布尔值呢?
function supplant(str, data) {
return str.replace(/{([^{}]*)}/g, function (a, b) {
// Split the variable into its dot notation parts
var p = b.split(/\./);
// The c variable becomes our cursor that will traverse the object
var c = data;
// Loop over the steps in the dot notation path
for(var i = 0; i < p.length; ++i) {
// If the key doesn't exist in the object do not process
// mirrors how the function worked for bad values
if(c[p[i]] == null)
return a;
// Move the cursor up to the next step
c = c[p[i]];
}
// If the data is a string or number return it otherwise do
// not process, return the value it was, i.e. {x}
return typeof c === 'string' || typeof c === 'number' ? c : a;
});
};
顺便说一句,它不支持数组,你需要做一些额外的事情来支持它。