题解 | #根据包名,在指定空间中创建对象#
根据包名,在指定空间中创建对象
http://www.nowcoder.com/practice/a82e035501504cedbe881d08c824a381
// 常规解法
function namespace(oNamespace, sPackage) { const packages = sPackage.split('.') let temp = oNamespace for (let idx in packages) { if(temp[packages[idx]] === undefined) { temp[packages[idx]] = {} } temp = temp[packages[idx]] } return oNamespace }
// 使用reduce
function namespace(oNamespace, sPackage) { sPackage.split('.').reduce((acc,cur) => { return typeof acc[cur] === 'object' ? acc[cur] : acc[cur] = {} }, oNamespace) }