我有一个问题,用匹配字符串字母的键替换对象的值。
挑战:创建一个函数secretCipher,接受一个字符串(句子)和一个对象(密码)。返回一个字符串,其中每个字符都被替换为密码中的对应值。如果密码中不存在该字符,则使用原字符
这是我到目前为止写的。我的console.log
显示了我需要它们的东西,但是当我试图识别与sentence[i]
相同的对应密钥时,我的挂断似乎在某个地方。我已经尝试了许多方法,如.includes
,严格相等等。
我也尝试使用.replace
来替换任何sentence[i]
与by值变量。
function secretCipher(sentence, cipher){
let result = '';
let cyf = Object.keys(cipher)
// console.log(cyf)
for (let key in cipher){
let value = cipher[key];
// console.log(value)
}
// iterate through sentence, if char in string is stricktly equal to the key
for (let i = 0; i < sentence.length; i++) {
// console.log(sentence[i])
if (sentence[i].includes(cyf)){
sentence[i] = sentence[i].replace(sentence[i], value)
result += sentence[i]
} else {
result += sentence[i]
}
}
return result;
}
//Uncomment the lines below to test your function:
console.log(secretCipher("lqq me on flcebzzk" , { l : "a", q : "d", z: "o"})); //=> "add me on facebook"
console.log(secretCipher("where are you???" , { v : "l", '?' : "!"})) //=> "where are you!!!"
console.log(secretCipher("twmce" , { m : "n", t : "d", w : "a"})); //=> "dance"
您可以更有效地遍历单词,但这非常简单:
function secretCipher(sentence, cipher){
return sentence.split('').map(letter => cipher[letter] ?? letter).join('');
}
//Uncomment the lines below to test your function:
console.log(secretCipher("lqq me on flcebzzk" , { l : "a", q : "d", z: "o"})); //=> "add me on facebook"
console.log(secretCipher("where are you???" , { v : "l", '?' : "!"})) //=> "where are you!!!"
console.log(secretCipher("twmce" , { m : "n", t : "d", w : "a"})); //=> "dance"
如果你的浏览器不知道什么?Is,用||代替。根据MDN,它应该可以在所有现代浏览器上运行。
let value = cipher[key];
不做任何事情,因为value
没有在其他任何地方被引用(它的作用域在循环迭代结束后结束)if (sentence[i].includes(cyf)) {
没有意义,因为sentence[i]
是一个字符串(字符),cyf
是一个键数组。字符串不包含数组。检查数组是否包含该字符。sentence[i] = sentence[i].replace(sentence[i], value)
不能工作,因为字符串是不可变的。创建一个新的字符串。- 当找到匹配时,添加原始
sentence[i]
没有意义-您想要替换对象上的值,而不是原始字符。
function secretCipher(sentence, cipher) {
let result = '';
const keys = Object.keys(cipher);
// iterate through sentence, if char in string is stricktly equal to the key
for (let i = 0; i < sentence.length; i++) {
if (keys.includes(sentence[i])) {
result += cipher[sentence[i]];
} else {
result += sentence[i]
}
}
return result;
}
console.log(secretCipher("lqq me on flcebzzk", {
l: "a",
q: "d",
z: "o"
})); //=> "add me on facebook"
console.log(secretCipher("where are you???", {
v: "l",
'?': "!"
})) //=> "where are you!!!"
console.log(secretCipher("twmce", {
m: "n",
t: "d",
w: "a"
})); //=> "dance"
或者更简洁地说
function secretCipher(sentence, cipher) {
let result = '';
for (const char of sentence) {
result += cipher[char] ?? char;
}
return result;
}
console.log(secretCipher("lqq me on flcebzzk", {
l: "a",
q: "d",
z: "o"
})); //=> "add me on facebook"
console.log(secretCipher("where are you???", {
v: "l",
'?': "!"
})) //=> "where are you!!!"
console.log(secretCipher("twmce", {
m: "n",
t: "d",
w: "a"
})); //=> "dance"