javascript - forEach() javascript 中未定义的变量
问题描述
使用这个简单的函数来遍历一个数组并显示元素、索引和类型,我试图为以元音开头的单词添加一个“n”到单词 a。例如。一个数字,一个对象。
但是添加 n 的变量“n”在最终的 console.log 中未定义
我相信它是一个范围错误,但对 javascript 不熟悉,我正在寻求帮助
const someArr = [
'max',
34,
true,
{
name: 'sandra',
student: true
},
['javascript', 'mongodb', 'react']
];
////////////////
function arrayTypeFinder(array) {
someArr.forEach((elem, index) => {
let type = typeof elem;
if (type.charAt(0) === "a" || "e" || "i" || "o" || "u") {
let n = "n"
} else {
let n = ""
}
console.log(`element ${elem} at index number: ${index} is a${n} ${type}`)
})
}
///////////
arrayTypeFinder(someArr) //=> n is not defined
解决方案
你需要定义外部if条件
let n = ""
if (type.charAt(0) === "a" || "e" || "i" || "o" || "u") {
n = "n"
}
或者你可以像这样使用
let n= (type.charAt(0) === "a" || "e" || "i" || "o" || "u") ? "n" :"";
推荐阅读
- amazon-web-services - 将 EBS 卷附加到 AutoScalingGroup
- javascript - Microsoft Edge Javascript 中的语法错误
- python-3.x - 即使缩进正确,pygame显示黑屏
- swift - 向 BLE 外围设备发送数据并检查是否已到达?
- php - 无法在 laravel 上捕获“Symfony\Component\HttpKernel\Exception\NotFoundHttpException”
- reactjs - 在基于类的组件中返回使用不同的括号
- strapi - 重置密码不需要 ReCaptcha 吗?
- file - 如何在颤振应用程序的资产文件夹中写入和读取文件?
- css - React - 构建 React 应用程序后 CSS 样式搞砸了
- java - 应用程序无法在 android 9 版本中运行,但在以下版本中运行