javascript - js如何實(shí)現(xiàn)這種操作,get(obj,’k1’,’k2’,’k3’).then((v)=>console.log(v))
問題描述
類似下面這種代碼
get(obj,’k1’,’k2’,’k3’) .then((v)=>console.log(v)) .else(()=>console.log(’值為空’));
實(shí)現(xiàn)下面這種代碼的功能
if(obj && obj.k1 && obj.k1.k2 && obj.k1.k2.k3){ console.log(obj.k1.k2.k3);}else{ console.log(’值為空’)}
問題解答
回答1:采用es6+promise實(shí)現(xiàn)方式
// 功能實(shí)現(xiàn)function get(obj, ...props) { // 檢查該對象是否擁有某個(gè)屬性 function hasProp(obj, prop) { return !!obj[prop] } return new Promise(function(resolve, reject) { let tempObj = {...obj} for (let i = 0; i < props.length; i++) { // 如果找到該屬性,將該屬性存儲(chǔ)起來繼續(xù)尋找下一個(gè)屬性,直到循環(huán)結(jié)束 if (hasProp(tempObj, props[i])) {tempObj = tempObj[props[i]] } else { // 找不到則返回錯(cuò)誤信息return reject(’找不到’ + props[i] + ’屬性’) } } return resolve(tempObj) })}// 使用let obj = { user: { name: ’anguer’ }}get(obj, ’user’, ’name’).then(function(res) { console.log(res) // print ’anguer’}).catch(function(err) { console.log(err)})回答2:
這樣行不行
function get (obj) { var scope = { obj: obj } var path = ’scope.obj.’ + Array.prototype.slice.call(arguments, 1).join(’.’) var value = null var NONE = ’值為空’ try {value = (new Function(’scope’, ’return ’ + path + ’;’))(scope)if (value === null || value === undefined) { return NONE } else { return value} } catch (e) {return NONE }}var obj = { k1: { k2: { k3: 1}}}get(obj, ’k1’, ’k2’, ’k3’) // 1get(obj, ’k1’, ’k’, ’k3’) // 值為空回答3:
class Tang { constructor() { this.obj = null; this.keys = []; this.thenF = []; this.elseF = []; } then(fn) { this.thenF.push(fn); return this; } _init() { let [obj, ...keys] = arguments; this.obj = obj; this.keys = keys; setTimeout(() => this._start(), 0) return this; } _start() { while(this.keys.length && this.obj) { this.obj = this.obj[this.keys.shift()]; } if (!this.keys.length) { this.thenF.forEach(fn => fn(this.obj)); } else { this.elseF.forEach(fn => fn()); } } else(fn) { this.elseF.push(fn); return this; }}let obj = {k1:{k2:{k3:1}}};let tang = new Tang();let get = tang._init.bind(tang);get(obj,’k1’,’k2’,’k3’) .then((v)=>console.log(v)) .else(()=>console.log(’值為空’));
看到鏈?zhǔn)秸{(diào)用我就想到了之前的lazyman。實(shí)現(xiàn)的比較丑陋。。。
回答4:參考一下
function get (obj, ...keys) { try { let value = keys.reduce((o, k) => o[k], obj) return { then (cb) {if (typeof cb === ’function’) { cb(value) }return {else () {}} } } } catch (e) { return { then () {return { else (cb) { if (typeof cb === ’function’) { cb(e) } }} } } }}
