JavaScript中的++ i和i ++有什么区别

编程入门 行业动态 更新时间:2024-10-25 10:27:42
本文介绍了JavaScript中的++ i和i ++有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在寻求学习和改进JavaScript的过程中,我遇到了一个带有switch/case语句的脚本,我注意到使用++在++之前加上一些变量,然后在++之后加上一些变量.变量.这些有什么区别?这是我要解释的示例,请注意m和y变量.

on my quest to learn and improve my JavaScript I came across a script that has a switch / case statement and I noticed some variables are incremented using ++ with the variable before the ++ and then some variables have the ++ after the variable. What's the difference between these? Here's an example of what I'm trying to explain notice the m and y variables.

switch(f){ case 0:{ ++m; if(m==12){ m=0; y++; } break; } case 1:{ --m; if(m==-1){ m=11; y--; } break; } case 2:{ ++y; break; } case 3:{ --y; break; } case 4:{ break; } }

推荐答案

++i在增加i的值后返回. i++在递增之前返回i的值.

++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing.

当++出现在其操作数之前时,它称为前递增"运算符,当它出现在其之后时,则称为后递增"运算符.

When the ++ comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator.

仅当您对结果进行某些操作时,这种区别才重要.

This distinction is only important if you do something with the result.

var i = 0, j = 0; alert(++i); // alerts 1 alert(j++); // alerts 0

要注意的一件事是,即使i++在递增之前返回该值,但在将其转换为数字后仍会返回该值.

One thing to note though is that even though i++ returns the value before incrementing, it still returns the value after it has been converted to a number.

所以

var s = "1"; alert(typeof s++); // alerts "number" alert(s); // alerts 2, not "11" as if by ("1" + 1)

更多推荐

JavaScript中的++ i和i ++有什么区别

本文发布于:2023-07-29 09:01:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!