2 回答
TA贡献1862条经验 获得超7个赞
您需要从函数返回对象,但也不应该在循环对象时从对象中删除键。
像这样的事情会做到这一点:
const removeVowelKeys = (obj) =>
Object.fromEntries(
Object.entries(obj).filter(
([k]) => !["a", "e", "i", "o", "u"].includes(k.toLowerCase()[0])
)
);
console.log(removeVowelKeys({
alarm: 'This is SPARTA!!!',
chip: 100,
isValid: false,
Advice: 'Learn it hard',
onClick: 'make it great again',
}));
我还修复了您的原始方法以在迭代对象之前复制对象,并使用[square bracket]符号来正确使用您的键:
function removeVowelKeys(obj) {
for (let key in { ...obj }) {
if (
key[0] === "a" ||
key[0] === "A" ||
key[0] === "u" ||
key[0] === "U" ||
key[0] === "i" ||
key[0] === "I" ||
key[0] === "o" ||
key[0] === "O" ||
key[0] === "e" ||
key[0] === "E" ||
key[0] === "y" ||
key[0] === "Y"
) {
delete obj[key];
}
}
return obj;
}
TA贡献1820条经验 获得超10个赞
我是这样做的。确保您实际上从函数中返回了一些内容...另请注意,y 在技术上不是元音。
function removeVowelKeys(obj) {
let output = {};
for (let key in obj) {
if (!(['a', 'e', 'i', 'o', 'u'].includes(key[0].toLowerCase()))) output[key] = obj[key];
}
return output;
}
添加回答
举报