個人的には、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;
});
};
それは配列をサポートしていません。それをサポートするには、いくつかの追加作業を行う必要があります。