我试图拆分一个输入的字符串,然后遍历一个对象数组,以便将字符串的每个部分与一系列拼写匹配(您可以看到下面的数据结构)。然而,我似乎只是返回undefined。
这是我的redux代码
const wordSlice = createSlice({
name: 'word',
initialState: { word: '', preppedWord: '' },
reducers: {
[...]
checkPhonemes(state, action) {
console.log(decoder.phonemeCheck(state.word))
state.preppedWord = decoder.phonemeCheck(state.word)
},
},
})以下是相关职能:
export const phonemeCheck = (word) => {
return phonemeMatcher(word)
}
///map((element) => { /* … */ })
export const phonemeMatcher = (word) => {
for (let i = 0; i < word.length; i++) {
for (let j = 0; j < word.length - i; j++) {
let chunk = word.substring(i, i + j + 1)
consonants.map((consonant) => {
consonant.spellings.map((spelling) => {
if (chunk === spelling.spelling) {
console.log(chunk)
return <span className={'phoneme-class'}>{chunk}</span>
}
})
})
}
}
}这是数据(节选)
export const consonants = [
//remember to wrap sounds in / / eg. /s/, /c/
{
consonantSound: 's',
spellings: [
{ spelling: 's', example: 'sun' },
{ spelling: 'ss', example: 'class' },
{ spelling: 'c', example: 'cell' },
{ spelling: 'ce', example: 'voice' },
{ spelling: 'se', example: 'house' },
{ spelling: 'sc', example: 'scent' },
],
},
{
consonantSound: 'sh',
spellings: [
{ spelling: 'sh', example: 'ship' },
{ spelling: 'ch', example: 'machine' },
],
},
{
consonantSound: 'ch',
spellings: [
{ spelling: 'tch', example: 'match' },
{ spelling: 'ch', example: 'chips' },
],
},
[..]
]发布于 2022-09-05 09:26:18
这样做是有效的:
export const phonemeCheck = (word) => {
return phonemeMatcher(word)
}
export const phonemeMatcher = (word) => {
const phonemes = new Set()
for (let i = 0; i < word.length; i++) {
for (let j = 0; j < word.length - i; j++) {
let chunk = word.substring(i, i + j + 1)
consonants.map((consonant) => {
consonant.spellings.map((spelling) => {
console.log(spelling.spelling)
if (chunk === spelling.spelling) {
phonemes.add(chunk)
}
})
})
}
}
return Array.from(phonemes).map((phoneme) => {
return <span className={'phoneme-class'}>/{phoneme}/</span>
})
}发布于 2022-09-05 09:29:59
创建一个集并在相同的地图上映射,这样您就不需要使用多个映射。
您可以返回如下内容:
return Array.from(set).map((element) => {
return <span className={'phoneme-class'}>/{element}/</span>
}https://stackoverflow.com/questions/73606367
复制相似问题