javascript - Why I get "Invalid left-hand side in assignment"? - Stack Overflow

There is code:function search(list, q){var result = {};for(let id in list)((!q.id|| (id == q.id)) &

There is code:

function search(list, q){
  var result = {};
  for(let id in list)(
    (!q.id    || (id == q.id)) &&
    (!q.name  || (list[id].name.search(q.name) > -1)) &&
    result[id] = list[id]
  );

  return result;
}

I get this error:

Uncaught ReferenceError: Invalid left-hand side in assignment    script.js:4

Why "&&" is wrong?

There is code:

function search(list, q){
  var result = {};
  for(let id in list)(
    (!q.id    || (id == q.id)) &&
    (!q.name  || (list[id].name.search(q.name) > -1)) &&
    result[id] = list[id]
  );

  return result;
}

I get this error:

Uncaught ReferenceError: Invalid left-hand side in assignment    script.js:4

Why "&&" is wrong?

Share Improve this question edited Dec 6, 2017 at 6:43 Vala Khosravi 2,5703 gold badges25 silver badges54 bronze badges asked Dec 1, 2017 at 3:30 Turar AbuTurar Abu 3681 gold badge3 silver badges12 bronze badges 5
  • are you missing if before the first set of parentheses? – Dan O Commented Dec 1, 2017 at 3:32
  • 1 result[id] = list[id] should be result[id] === list[id] as it is a condition – Aravind Commented Dec 1, 2017 at 3:33
  • @Aravind that is not correct. – Pointy Commented Dec 1, 2017 at 3:38
  • @DanO "if" must not be important, because all logical operator in ( ), not { } – Turar Abu Commented Dec 1, 2017 at 3:43
  • @TurarAbu see my answer: the problem is that your assignment expression at the end of the && list is not in parentheses. – Pointy Commented Dec 1, 2017 at 3:43
Add a ment  | 

2 Answers 2

Reset to default 7

The problem is that the assignment operator, =, is a low-precedence operator, so it's being interpreted in a way you don't expect. If you put that last expression in parentheses, it works:

  for(let id in list)(
    (!q.id    || (id == q.id)) &&
    (!q.name  || (list[id].name.search(q.name) > -1)) &&
    (result[id] = list[id])
  );

There seems to be a typo in your code:

result[id] = list[id] should be result[id] == list[id] or result[id] === list[id](if you're doing a strict parison)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743680473a4489295.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信