统计字符串出现次数
// 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))
}