JavaScript类数组与Array.form()

认识类数组

有下标和length

const obj = {
    
    
  0: 1,
  1: 3,
  length: 2,
}
const arr = Array.from(obj)
console.log(arr) // [1, 3]

相关问题

假设给obj一个push方法,并且push一个数会产生什么效果?

const obj = {
    
    
  0: 1,
  2: 3,
  length: 2,
  push: [].push
}

obj.push(4)

console.log(obj) // { 0: 1, 2: 4, length: 3, push: f push() }

这里发现obj[2]的值变成了4,且length+1,所以这里push的过程就是obj[obj.length] = 4-> length + 1,如果把length变成1再看看效果:

const obj = {
    
    
  0: 1,
  2: 3,
  length: 1,
  push: [].push
}

obj.push(4)

console.log(obj) // { 0: 1, 1: 4, 2: 3, length: 2, push: f push() }

Array.from()

Array.from()可以将一个类数组转为数组,具体生成规则如下:

    const obj = {
    
    
      0: 1,
      2: 3,
      // 类数组中的length决定生成的数组的长度,length默认值为0
      // 根据length值与符合的属性个数,对生成的数组进行裁剪与增加(无值为undefined)
      // 这里没有1这个属性,所以arr[1] = undefined,arr数组长度为2,所以就没有arr[2]了
      length: 2,
    }

    const arr = Array.from(obj)

    console.log(arr) // [1, undefined]

如果没有length属性

const obj = {
    
    
  0: 1,
  2: 3,
  // 类数组中的length决定生成的数组的长度,length默认值为0
  // 根据length值与符合的属性个数,对生成的数组进行裁剪与增加(无值为undefined)
  // length: 2,
}

const arr = Array.from(obj)

console.log(arr) // []

Array.from()的参数:
具体可看MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Array.from(arrayLike, mapFn, thisArg)

// arrayLike: 目标类数组
// mapFn(可选): 回调函数(可以对数组每一项进行处理)
// thisArg(可选):执行回调函数mapFn时的this对象,这里可以将mapFn会用到的一些配置写在这里

以下为具体示例:

const obj = {
    
    
  0: 1,
  1: 2,
  2: 3,
  length: 3,
}

// 这里不要用箭头函数,可以思考一下为什么
const arr = Array.from(obj, function (value, key) {
    
    
  return {
    
    
    name: `${
      
      this.title} ${
      
      value}`,
    order: key
  }
}, {
    
    
  title: 'this is'
})

console.log(arr)
// [
//   { name: 'this is 1', order: 0 },
//   { name: 'this is 2', order: 1 },
//   { name: 'this is 3', order: 2 },
// ]

猜你喜欢

转载自blog.csdn.net/Wind_AN/article/details/124720331