【问题标题】:Getting an Unexpected identifier at createScript error在 createScript 错误时获取意外的标识符
【发布时间】:2018-05-24 02:56:11
【问题描述】:

为什么我收到此代码的错误?我要做的就是返回一个包含多个参数的数组。

function multiplyByTwo(a,b,c){
 //we have two variables i and ar which is an array
 var i,ar=[];
 //for loop cycles through 0-2 and multiplies each by two
 for(int i=0;i<3;i++){
//  arguments[3] // Takes the arguem Follows array indexing notations. 
//at i=0, ar[0]=arguments[0]*2, arguments[0]=a*2
//at i=1, ar[1]=arguments[1]*2, arguments[1]=b*2
//at i=2, ar[2]=arguments[2]*2, arguments[2]=c*2
ar[i]=arguments[i]*2;
    }
 return ar;
}

var result=multiplyByTwo(1,2,3);



Error: SyntaxError: Unexpected identifier
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)

【问题讨论】:

  • for(int i=0;i&lt;3;i++){ Vanilla JS 没有int。将来您可以通过查看错误所指的行自己找出问题
  • 应该是for (var i = 0; ...)
  • 啊,谢谢,java的习惯,哈哈

标签: javascript arrays error-handling stack-trace


【解决方案1】:

正如cmets中的人所说,错误的主要原因是JS中没有int。有一些改进/建议可以重构您的代码,如下所示:

function multiplyByTwo(...args){
  var i,ar=[];

  for(let i=0;i<arguments.length;i++){
    ar[i]=arguments[i]*2;
  }
 return ar;
}

var result=multiplyByTwo(1,2,3,4);

首先,方法multiplyByTwo(...args)。使用 Spread syntax 可以让您的函数接收动态数量的参数,而不是硬编码为 3 个固定长度,从而提高函数的可扩展性。

由于您使用关键字arguments,为了保持一致,而不是恰好循环3次,将其替换为arguments.length,它将补充前面建议的...args。当然,还有其他更简单、更短的语法可用于实现您正在做的事情,如下所示

function multiplyByTwo(...args){
  return [...args].map(x => x * 2);
}

var result=multiplyByTwo(1,2,3,4);
console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2015-01-28
    • 1970-01-01
    • 2014-07-25
    • 2015-06-15
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多