为什么我的Javascript增量运算符(++)在我的addOne函数中无法正常工作 [英] Why is my Javascript increment operator (++) not working properly in my addOne function

查看:57
本文介绍了为什么我的Javascript增量运算符(++)在我的addOne函数中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人可以向我解释为什么我的addOne函数不能与增量运算符(++)一起使用.请在下面查看我的代码.

Please can someone explain to me why my addOne function doesn't work with the increment operator (++). Please see my code below.

// addOne Function

function addOne(num){
  return num + 1
}

log(addOne(6)) => 7


// same function with ++ operator

function addOne(num){
  return num++
}

log(addOne(6)) => 6


// Question - why am I getting 6 instead of 7 when I use ++ operator?

推荐答案

有两个增量运算符:前缀和后缀.

There are two increment operators: prefix and postfix.

后缀运算符使变量之后递增.例如,以下代码产生11,因为它加了5和6:

The postfix operator increments the variable after it is evaluated. For example, the following code produces 11, because it adds 5 and 6:

var a = 5;
(a++) + (a++)

前缀运算符使变量 before 递增.听起来就是您想要的.以下代码产生13,因为它加了6和7:

The prefix operator increments the variable before it is evaluated. Sounds like that is what you want. The following code produces 13, because it adds 6 and 7:

var a = 5;
(++a) + (++a)

因此您的代码应为:

function addOne(num) {
  return ++num;
}

console.log(addOne(6));

这篇关于为什么我的Javascript增量运算符(++)在我的addOne函数中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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