我個人討厭它,當人們在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;
});
};
它不支持數組btw,你需要做一些額外的東西來支持。
這應有助於:http://stackoverflow.com/questions/4343028/in-javascript-test-for-property-deeply-nested-in-object-graph –