js高级写法

一、检查对象是否存在某属性( hasOwnProperty 和 in )

let Object = { name: '' }
//第一种 hasOwnProperty
console.log(Object.hasOwnProperty('name')) //true
//第二种 in
console.log('name' in Object) //true

二、检查数组是否存在某属性(includes)

        includes可以检测NaN,indexOf不能检测NaN,includes内部使用了Number.isNaNNaN进行了匹配

const A = ['a', 'b', 'c', 'd']
console.log(A.includes('a')) //true

三、更简单地使用indexOf实现是否存在元素(!!~)

//原本写法 
var A = 'javaScript is a scripting language'
if (A.indexOf('javaScript') !== -1) {
  console.log('存在') //存在
}
//现在写法
console.log(!!~A.indexOf('javaScript')) //true

四、将带有length属性的对象转化为数组(Array.prototype.slice.call和Array.from)

var object = { length: 2, 0: 'apple', 1: 'pear' }
//第一种
const Arr1 = Array.prototype.slice.call(object)
//第二种
const Arr2 = Array.from(object)
console.log(Arr1,Arr2) //[ 'apple', 'pear' ] [ 'apple', 'pear' ]

五、判断类型是否正确( instanceof )

let arr = [1, 2, 3]
let obj = { 0: 'apple', 1: 'pear', 2: 'banana' }
console.log(arr instanceof Array, obj instanceof Array) //true false

六、合并数组和对象(扩展运算符...)

const arr1 = [1, 2, 3, 4]
const arr2 = [1, 3, 5, 7]
let Arr = [...new Set([...arr1, ...arr2])]
const obj1 = { a: 1, b: 2 }
const obj2 = { c: 3, d: 4 }
let Obj = { ...obj1, ...obj2 }
console.log(Arr, Obj) //[ 1, 2, 3, 4, 5, 7 ] { a: 1, b: 2, c: 3, d: 4 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值