下面代码实现通过’a.b.c’连写的方式实现object的取值:getValue(obj, ‘a.b.c’ // {name: ‘Martin’})
代码
const obj = {
a: {
b: {
c: {
name: 'Martin'
}
}
}
}
// 函数封装
function getValue(obj, keys) {
if (typeof keys !== 'string') {
throw new Error('参数类型错误')
}
const list = keys.split('.')
const len = list.length
for(let i = 0; i < len; i++) {
const item = obj[list[i]]
if ( item !== undefined) {
obj = item
} else {
throw new Error('参数路径有误')
}
}
return obj
}
// 原型上封装
Object.prototype.getValue = function (keys) {
if (typeof keys !== 'string') {
throw new Error('参数类型错误')
}
const list = keys.split('.')
const len = list.length
let newObj = this
for(let i = 0; i < len; i++) {
const item = newObj[list[i]]
if ( item !== undefined) {
newObj = item
} else {
throw new Error('参数路径有误')
}
}
return newObj
}
// 输出结果
console.log(getValue(obj, 123)) // 报错:参数类型错误
console.log(getValue(obj, 'a.b.e')) // 报错:参数路径有误
console.log(getValue(obj, 'a.b.c')) // {name: 'Martin'}
console.log(obj.getValue(123)) // 报错:参数类型错误
console.log(obj.getValue('a.b.e')) // 报错:参数路径有误
console.log(obj.getValue('a.b.c')) // {name: 'Martin'}