JavaScript:期望和赋值或函数调用,而是看到一个表达式 [英] JavaScript : Expected and assignment or function call and instead saw an expression

查看:105
本文介绍了JavaScript:期望和赋值或函数调用,而是看到一个表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSHint来确保我的JavaScript处于严格"状态,并且出现以下错误:

I am using JSHint to ensure my JavaScript is "strict" and I'm getting the following error:

期望了一个赋值或函数调用,而是看到了一个表达式

使用以下代码:

      var str = 'A=B|C=D'
      var data = {};
      var strArr = str.split( '|' );
      for (var i = 0; i < strArr.length; i++) {
          var a = strArr[i].split('=');
          a[1] && (data[a[0].toLowerCase()] = a[1]);  // Warning from JSHint
      } 

关于为什么出现此类错误或如何编写代码以消除该错误的任何想法.

Any ideas why I'm getting such an error or how I can code to remove the error.

推荐答案

以下是给出相同警告的简化版本:

Here is a simplified version that gives the same warning:

var a, b;
a && (b = a);

期望了一个赋值或函数调用,而是看到了一个表达式

Expected an assignment or function call and instead saw an expression

这意味着您有一个表达式,但不将结果分配给任何变量. jshint不在乎实际的表达式是什么,也没有副作用.即使您在表达式内部分配了某些内容,您仍然忽略了表达式的结果.

This means that you have an expression but do not assign the result to any variable. jshint doesn't care about what the actual expression is or that there are side effects. Even though you assign something inside of the expression, you are still ignoring the result of the expression.

如果您关心jslint的另一个错误:

There is another error by jslint if you care about it:

意外的赋值表达式

Unexpected assignment expression

这会警告您,您可能想在逻辑表达式中使用==而不是=.这是一个常见错误,因此不建议您在逻辑表达式中使用赋值(即使这正是您想要的).

This warns you that you may want to use == instead of = inside logical expressions. It's a common error, therefore you are discouraged to use assignments in logical expressions (even though it is exactly what you want here).

基本上,jshint/jslint不喜欢滥用逻辑运算符的快捷方式评估来代替if语句.它假定如果不使用表达式的结果,则可能不应该是表达式.

Basically, jshint/jslint do not like misuse of shortcut evaluation of logical operator as replacement for if statements. It assumes that if the result of an expression is not used, it probably shouldn't be an expression.

这篇关于JavaScript:期望和赋值或函数调用,而是看到一个表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆