JavaScript中的后缀和前缀增量 [英] Postfix and prefix increments in JavaScript

查看:76
本文介绍了JavaScript中的后缀和前缀增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇一件事。 Javascript中的一个小例子

I'm just curious about one thing. A little example in Javascript

var a = 1;
a = a++;
console.log(a); // 1

var b = 1;
b = ++b;
console.log(b); // 2

var c = 1;
c += 1;
console.log(c); //2

我理解为什么它以这种方式工作以防 b c ,但是 a 呢?
首先,代码进行赋值 a = a ,实际值保持不变,但是它应该(如我所见)增加并增加值<每单位code> a 。但这没有发生。为什么?

I understand why it works this way in case b and c, but what about a? At first the code makes an assignment a = a, the value stays the same actually, but then it should (as I see) make increment and increase value a per unit. But this not happening. Why?

推荐答案


var a = 1;
a = a++;





  1. 1 分配给 a

  2. a ++ 被评估为 1

  3. a ++ 增量 a 2

  4. a = {以前的评估结果} 1 分配给 a 所以它是 1 再次

  1. 1 is assigned to a
  2. a++ is evaluated as 1
  3. a++ increments a to 2
  4. a = {result of previous evaluation} assigns the 1 to a so it is 1 again




var b = 1;
b = ++b;





  1. 1 分配给 b

  2. ++ b 增量 b 2

  3. + + b 评估为 2

  4. b = {先前评估的结果} 2 分配给 b 所以它是 2 仍然

  1. 1 is assigned to b
  2. ++b increments b to 2
  3. ++b is evaluated as 2
  4. b = {result of previous evaluation} assigns the 2 to b so it is 2 still

这篇关于JavaScript中的后缀和前缀增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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