代码之家  ›  专栏  ›  技术社区  ›  Bibberty

使用import语句时,为什么会出现“未捕获的SyntaxError:意外标识符”失败

  •  1
  • Bibberty  · 技术社区  · 6 年前

    所以我试着测试一下 import myFunction from './mymodules.js' . 在Chrome中打开,我得到了错误- Uncaught SyntaxError: Unexpected identifier

    以下是回复: https://repl.it/@PaulThomas1/ModulePractice

    我正在看这篇文章: https://developers.google.com/web/fundamentals/primers/modules

    export default function findInArray(arr, search) {
      if(Array.isArray(arr) == false) return Error("arr - Is not an array");
      if(search == undefined) return Error("search - Undefined");
    
      let searchMethod;
    
      if(typeof search == 'string') {
          searchMethod = (element) => { 
            return search == element;
          };
        } else {
          searchMethod = (element) => {
            return search(element);
          };
        }
    
      arr.forEach(element => {
        if(searchMethod(element)) {
          return element;
        }
      });
    
      return '';
    }
    

    尝试导入此内容的我的Javascript:

    import findInArray from './modules/util.js';
    
    let myArray = ["Bill", "Bob", "Ben"];
    
    console.log(findInArray(myArray, "Bob"));
    

    我已经读了好几页了,但是没有这方面的内容。 我是不是做错了什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Andy    6 年前

    看起来有几个问题:

    1) 你只需要加载 script.js type="module"

    <script type="module" src="script.js"></script>
    

    2) 在 util 您无法从的回调返回 forEach filter find 要根据需要返回新数组或对象,请执行以下操作:

    return arr.filter(element => searchMethod(element));