首页 > 解决方案 > 如何检查传递给 JavaScript 函数的参数类型?

问题描述

我想确保传递给函数的参数是元素而不是数字或字符串,这样我的程序就不会崩溃?

function myFunction(element){ 
  console.log(element.style.color)
}

标签: javascript

解决方案


也许您正在寻找HTMLElement

function myFunction(element) {
  if (element instanceof HTMLElement) {
    console.log(element.style.color)
  }
}

推荐阅读