JavaScript 字符串数组编程题合集

统计字符串出现次数

// 1.for实现
const str = 'abcdefg'
const obj = {}
for (const i in str) {
  if (obj[str[i]]) {
    obj[str[i]]++
  } else {
    obj[str[i]] = 1
  }
}
// 2.不用for实现
console.log(str.split('').reduce((obj, item) => {
  obj[item]++ || (obj[item] = 1)
  return obj
}, {}))

字符串翻转

// 1.for实现
str.split('').forEach(item => (str = item + str.replace(item, '')))
// 2.不用for循环实现
str.split('').reverse().join('')

找出最长单词,并返回该单词

const str = 'Find the Longest Word in a String'
let str1 = ''
str.split(' ').forEach(item => {
  (item.length > str1.length) && (str1 = item)
})

确保字符串的每个单词首字母都大写

// const str = 'Title case a sentence'
// str.split(' ').map(item => item.replace(item[0], item[0].toUpperCase())).join(' ')

找出多个数组中的最大数,并按照从小到大的排序,得到一个最大数集合的数组

const arr = [[1000, 1001, 857, 1], [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39]]
const tempArr = arr.map(item => {
  let maxVal = ''
  item.forEach(item1 => {
    (item1 > maxVal) && (maxVal = item1)
  })
  return maxVal
})
const newArr = []
for (let i = 0; i < tempArr.length; i++) {
  newArr.unshift(Math.max(...tempArr))
  tempArr.indexOf(Math.max(...tempArr))
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值