JavaScript 字符串技巧

JavaScript 字符串技巧


// 多个分隔符上拆分字符串

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]

// 我们经常会写这样的判断语句,当其中一个条件满足时做某事。

const num = 1
if (num === 1 || num === 2 || num === 3 || num === 4) {
  console.log(num) // 1
}

// 其实可以通过includes方法来简化代码。

const nums = [ 1, 2, 3, 4 ]
const num = 1
if (nums.includes(num)) {
  console.log(num) // 1
}

// flat(Infinity)可展开任意嵌套的数组

const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
const flatAll = array.flat(Infinity) // [ 1, 2, 3, 4, 5 ]

// at 可以读取数组中其他位置的元素。

const array = [ 1, 2, 3, 4, 5 ]
const lastEle = array.at(-1) // 5
const ele1 = array.at(0) // 1

//findIndex() 方法返回数组中满足所提供的测试函数的第一个元素的索引。否则,返回-1,表示没有元素通过测试。

const array = [ -1, 0, 10, 10,  20, 100 ]
const index1 = array.findIndex((num) => num < 0) // 0
const index2 = array.findIndex((num) => num >= 10) // 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值