Array、Object方法

Array.from()

对象转数组 只要有length属性都能转成数组

Array.of() 将一组值,转换为数组。

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组

entries(),keys() 和 values()

keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历 
let obj = {
    a: 1,
    b: 2,
    c: 3
}

console.log(Object.keys(obj))         // ['a', 'b', 'c']

console.log(Object.values(obj))       // [1, 2, 3]

console.log(Object.entries(obj))      // [['a', 1], ['b', 2], ['c', 3]]

Array.sort()

let b = [33, 4, 1111, 22, 4]
alert(b.sort((a,b)=>{return a-b}))  //4,4,22,33,1111

let c =['ant','Dog','cut','Bug']
alert(c.sort((a,b)=>{
	const c = a.toLowerCase()
	const d = b.toLowerCase()
	return c - d
})) //ant,Dog,cut,Bug

Array.reduce()

let d = [1,2,3,4,5]
const dd = d.reduce((a,b)=>{
	return a+b
},0)
console.log(dd) //15

Array.reduceRight()

includes()

Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的
includes方法类似。

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true

flat(),flatMap()

Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数
据没有影响,flat()参数默认为1。
[1, 2, [3, 4]].flat()           // [1, 2, 3, 4]
[1, 2, [3, [4, 5]]].flat()      // [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)     // [1, 2, 3, 4, 5]
[1, [2, [3]]].flat(Infinity)    // [1, 2, 3] 可以用Infinity关键字作为参数
[1, 2, , 4, 5].flat()           // [1, 2, 4, 5] 如果原数组有空位,flat()方法会跳过空位

flatMap()方法对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),然后对返回
值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

Object.is()

相等运算符(==)和严格相等运算符(===)。它们都有缺点,前者会自动转换数据类型,后者的NaN
不等于自身,以及+0等于-0,Object.is就是用来解决这个问题,与“===”基本一致。

+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

Object.assign() 浅拷贝

Object.assign方法用于对象的合并。
Object.assign(arr1, arr2, arr3);
Object.assign(undefined) // 报错
Object.assign(null) // 报错 undefined和null无法转成对象(不在首位不会报错)

注意    const target = { a: { b: 'c', d: 'e' } }
        const source = { a: { b: 'hello' } }
        Object.assign(target, source)
        // { a: { b: 'hello' } }
posted @ 2020-06-19 10:42  小白是鱼骨头呀!  阅读(515)  评论(0编辑  收藏  举报