gpt4 book ai didi

javascript - 如何通过检查对象的值来保持构造字符串的间距

转载 作者:行者123 更新时间:2023-12-04 07:48:37 26 4
gpt4 key购买 nike

返回一个字符串,该字符串将字符替换为其在字符串中受尊重的值,
如果该字符不存在,则添加“?”到您的结果字符串中。
记住在两者之间保持空间。
我的问题是我无法在结果字符串中创建空格。我的条件语句有问题吗?

var dict = {a: 'e',
s: 'o',
b: 't',
g: 'q'
};

function second(str, obj) {
let result = '';

for (let i = 0; i < str.length; i++) {
if (obj[str[i]] === undefined) {
result += '?';
}
else if (obj[str[i]]!== undefined && str[i] !== ' ') {
result += obj[str[i]];
} else if (obj[str[i]] !== undefined && str[i] === ' ') {
result += ' ';
}
}
return result;
}


console.log(second('hi bro what is going on', dict)); // '?? t?? ??e? ?o q???q ??'

最佳答案

问题是 if (obj[str[i]] === undefined) {检查 - 对象中不存在空格,因此它连接了 ? .
您可以在 dict 中添加一个空格来修复它:

var dict = {a: 'e',
s: 'o',
b: 't',
g: 'q',
' ': ' '
};

function second(str, obj) {
let result = '';

for (let i = 0; i < str.length; i++) {
if (obj[str[i]] === undefined) {
result += '?';
} else result += obj[str[i]];;
}
return result;
}


console.log(second('hi bro what is going on', dict)); // '?? t?? ??e? ?o q???q ??'

或者,如果您无法修改 dict:

var dict = {a: 'e',
s: 'o',
b: 't',
g: 'q'
};

function second(str, obj) {
let result = '';
for (const char of str) {
if (char === ' ') result += ' ';
else if (obj[char]) result += obj[char];
else result += '?';
}
return result;
}


console.log(second('hi bro what is going on', dict)); // '?? t?? ??e? ?o q???q ??'

或者使用正则表达式来匹配单词字符:

var dict = {a: 'e',
s: 'o',
b: 't',
g: 'q'
};

const second = (str, obj) => str.replace(
/\w/g,
char => dict[char] ?? '?'
);

console.log(second('hi bro what is going on', dict)); // '?? t?? ??e? ?o q???q ??'

关于javascript - 如何通过检查对象的值来保持构造字符串的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67083764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com