首页 > 解决方案 > 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

标签: javascriptforeachundefinedtypeof

解决方案


你需要定义外部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" :"";

推荐阅读