有哪些JavaScript单行代码在开发中最为常用?

更新于
2026-10-03 06:55:01
0阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1757个文字,预计阅读时间需要8分钟。

1. 强制布尔值+要将变量强制转换为布尔值而不改变其值:const myBoolean=!!myVariable; !!null // false !!undefined // false !!false // false !!true // true !! // false !!string // true !!0 // false !!1 // true {} // true

1.强制布尔值

要将变量强制转换为布尔值而不更改其值:

const myBoolean = !! myVariable; !!null // false !!undefined // false !!false // false !!ture // ture !!"" // false !!"string" // true !!0 // false !!1 // true !!{} // true !![] // true

2.基于某个条件为对象设置属性

要使用spread运算符有条件地在对象上设置属性:

const myObject = {... myProperty && {propName:myPoperty}}; let myProperty = 'Jhon' const myObject = {...myProperty && {propName: myProperty}}; // {propName: "Jhon"} let myProperty = '' const myObject = {...myProperty && {propName: myProperty}}; // {}

如果myProperty结果为false,则 && 失败并且不设置新属性; 否则,如果不为空,&& 将设置新属性并覆盖原来的值。

阅读全文

本文共计1757个文字,预计阅读时间需要8分钟。

1. 强制布尔值+要将变量强制转换为布尔值而不改变其值:const myBoolean=!!myVariable; !!null // false !!undefined // false !!false // false !!true // true !! // false !!string // true !!0 // false !!1 // true {} // true

1.强制布尔值

要将变量强制转换为布尔值而不更改其值:

const myBoolean = !! myVariable; !!null // false !!undefined // false !!false // false !!ture // ture !!"" // false !!"string" // true !!0 // false !!1 // true !!{} // true !![] // true

2.基于某个条件为对象设置属性

要使用spread运算符有条件地在对象上设置属性:

const myObject = {... myProperty && {propName:myPoperty}}; let myProperty = 'Jhon' const myObject = {...myProperty && {propName: myProperty}}; // {propName: "Jhon"} let myProperty = '' const myObject = {...myProperty && {propName: myProperty}}; // {}

如果myProperty结果为false,则 && 失败并且不设置新属性; 否则,如果不为空,&& 将设置新属性并覆盖原来的值。

阅读全文