如何解决forEachjavascript中未定义的变量
使用此简单函数遍历数组并显示元素,索引和类型,im尝试为以元音开头的单词在单词a上添加“ n”。例如。一个数字,一个对象。
但是添加n的变量“ n”在最终控制台中未定义。
我相信它的作用域错误,但是是javascript im寻求帮助的新手
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
解决方法
您需要在条件之外定义外部
let n = ""
if (type.charAt(0) === "a" || "e" || "i" || "o" || "u") {
n = "n"
}
或者您可以这样使用
let n= (type.charAt(0) === "a" || "e" || "i" || "o" || "u") ? "n" :"";
,
一种选择是使用[Unit]
Before=network-pre.target
Wants=network-pre.target
[Service]
# braise enable ensures hooks are setup into the network manager.
ExecStart=/usr/bin/braise enable
# The firewall is called by the nework manager.
RemainAfterExit=yes
ExecReload=/usr/bin/braise reload
[Install]
WantedBy=multi-user.target
而不是var
。
这样,在所有相关范围内声明了let
。分配前具有n
的值:
undefined
,
结合使用您的答案就可以了!谢谢!
function arrayTypeFinder(array) {
someArr.forEach((elem,index) => {
let type = typeof elem;
let n = (type.charAt(0) === "a" || type.charAt(0) === "e" || type.charAt(0) === "i" || type.charAt(0) === "o" || type.charAt(0) === "u") ? "n" : "";
console.log(`element ${elem} at index number: ${index} is a${n} ${type}`)
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。