Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

写了一个公共方法,使用_this实现迭代报错

image

const Other = {
  deepClone: (target)=>{
    // 定义一个变量
    let _this = this
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
      // 如果是一个数组的话
      if (Array.isArray(target)) {
        result = []; // 将result赋值为一个数组,并且执行遍历
        for (let i in target) {
          // 递归克隆数组中的每一项
          // result.push(_this.deepClone(target[i]))
          result.push(_this.deepClone(target[i]))
        }
        // 判断如果当前的值是null的话;直接赋值为null
      } else if(target===null) {
        result = null;
        // 判断如果当前的值是一个RegExp对象的话,直接赋值
      } else if(target.constructor===RegExp){
        result = target;
      } else {
        // 否则是普通对象,直接for in循环,递归赋值对象的所有值
        result = {};
        for (let i in target) {
          result[i] = _this.deepClone(target[i]);
        }
      }
      // 如果不是对象的话,就是基本数据类型,那么直接赋值
    } else {
      result = target;
    }
    // 返回最终结果
    return result;
  }
}

export { Other }

改了代码之后

image
image

const Other = {
  deepClone: function (target) {
    // 定义一个变量
    let _this = this
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
      // 如果是一个数组的话
      if (Array.isArray(target)) {
        result = []; // 将result赋值为一个数组,并且执行遍历
        for (let i in target) {
          // 递归克隆数组中的每一项
          // result.push(_this.deepClone(target[i]))
          result.push(_this.deepClone(target[i]))
        }
        // 判断如果当前的值是null的话;直接赋值为null
      } else if(target===null) {
        result = null;
        // 判断如果当前的值是一个RegExp对象的话,直接赋值
      } else if(target.constructor===RegExp){
        result = target;
      } else {
        // 否则是普通对象,直接for in循环,递归赋值对象的所有值
        result = {};
        for (let i in target) {
          result[i] = _this.deepClone(target[i]);
        }
      }
      // 如果不是对象的话,就是基本数据类型,那么直接赋值
    } else {
      result = target;
    }
    // 返回最终结果
    return result;
  }
}

export { Other }
let userData = []
        let cols = {}
        // console.log('list data == ', data)
        data.data.data.map((item, index)=>{
          // let itemNew = _this.deepClone(item)
          let itemNew = ObjectHelper.deepClone(item)
          console.log(`list item ${index} == `, item)
          userData[index] = itemNew
        })

        console.log('userData == ', userData)

为什么userData里面的数据是undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
deepClone: (target)=>{

不用箭头函数,改为

deepClone: function (target){

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...