您可以使用map
和reduce
来获取每个单词的值。您还可以将单词的索引与值一起存储,然后将值从高到低排序,然后直接使用[0]访问最大值,并通过索引[1]直接访问单词。
let testStr = 'man i need a taxi up to ubud'
const values = [...Array(27).keys()]
values.shift()
const keys = String.fromCharCode(...[...Array('z'.charCodeAt(0) - 'a'.charCodeAt(0) + 1).keys()]
.map(i => i + 'a'.charCodeAt(0)))
const merged = [...keys].reduce((obj,key,index) => ({ ...obj,[key]: values[index] }),{})
console.log(
testStr.split(' ')
.map(w => [w.split('').reduce((a,l) => (a += merged[l] || 0),0),w])
.sort(([a],[b]) => b - a)[0][1]
)
然后您可以将其转换为util函数:
const values = [...Array(27).keys()]
values.shift()
const map = [...String.fromCharCode(...[...Array('z'.charCodeAt(0) - 'a'.charCodeAt(0) + 1).keys()]
.map(i => i + 'a'.charCodeAt(0)))].reduce((obj,[key]: values[index]}),{})
const getHighest = s => (
s.toLowerCase()
.split(' ')
.map((w,i) => [w.split('').reduce((a,l) => (a += map[l] || 0),[b]) => b - a)[0][1]
)
console.log(getHighest('man i need a taxi up to ubud'))
console.log(getHighest('This is a test'))
但是,在循环中而不是事先在映射中获取值时,编写起来更容易,更短:
const getHighest = s => (
s.toLowerCase()
.split(' ')
.map((w,l) => (a += l.charCodeAt() || 0),[b]) => b - a)[0][1]
)
console.log(getHighest('man i need a taxi up to ubud'))
console.log(getHighest('This is a test'))
,
if items.selectedOption == 1 {
lblSubTotal.text = "$\(formatter.string(for: items.price1)!)"
lblWeight.text = "\(items.weight1)"
} else if items.selectedOption == 2 {
lblSubTotal.text = "$\(formatter.string(for: items.price2)!)"
lblWeight.text = "\(items.weight2)"
} else if items.selectedOption == 3 {
lblSubTotal.text = "$\(formatter.string(for: items.price3)!)"
lblWeight.text = "\(items.weight3)"
}
本文链接:https://www.f2er.com/3137099.html