工作中的一些方法

99 阅读1分钟

1、Object.assign()方法

对象的浅拷贝

2、整数的转换之加法篇

let str = '123' // 必须是纯数字
console.log(typeof +str); //number

3、有条件地向对象添加属性

const condition = true; 
const person = { 
id: 1, 
name: 'John Doe',
...(condition && { age: 16 }), 
};

4、使用 in 关键字来检查 JavaScript 对象中是否存在某个属性

const person = { 
    name: 'aa智', 
    salary: 1000 
}; 
console.log('salary' in person); // true 
console.log('age' in person); // false

5、检查一个变量是否为 null 或 undefined 时,区别于 || ,JavaScript 双问号也称为空值合并运算符。这个运算符只会在左侧表达式是 null 或 undefined 时返回右侧的表达式。

不同于逻辑或,空值合并运算符会允许把 0 和空字符串作为有效的数值

const foo = null ?? 'Hello'; 
console.log(foo); // 'Hello' 
const bar = 'Not null' ?? 'Hello'; 
console.log(bar); // 'Not null' 
const baz = 0 ?? 'Hello'; 
console.log(baz); // 0

6、!! 运算符可用于将表达式的结果快速转换为布尔值(truefalse)

const greeting = 'Hello there!'; 
console.log(!!greeting) // true 
const noGreeting = ''; 
console.log(!!noGreeting); // false

7、parseInt用法

let fool = '1231424'
console.log(parseInt(fool) // 1231424
let fool = '11a'
console.log(parseInt(fool) // 11
let fool = 'a11'
console.log(parseInt(fool) //NaN

8、Object.getPrototypeOf()方法

返回指定对象的原型