在javascript中解释+ var和-var一元运算符 [英] Explain +var and -var unary operator in javascript

查看:89
本文介绍了在javascript中解释+ var和-var一元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在javascript中理解一元运算符,我在这里找到了这个指南 http:// wiki。 answers.com/Q/What_are_unary_operators_in_javascript 大部分都有意义,但我不明白的是如何在实际代码示例中使用以下示例:

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:

+a;
-a;

根据我的理解, + a; 旨在使变量成为a的正值和 -a; 意味着使变量成为a的负值。我尝试了很多例子:

To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:

a = -10;
a = +a;
document.writeln(a);

输出仍为-10;

我也尝试过:

a = false;
a = +a;
document.writeln(a);

输出为0;

这些一元运算符的实际代码示例是什么?

What is a practical code example of these unary operators?

推荐答案

+ 运算符不会更改值的符号, - 运算符会更改符号。两个运算符的结果取决于原始值的符号,无论原始符号如何,运算符都不会使值为正或负。

The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.

var a = 4;
a = -a; // -4
a = +a; // -4

abs 函数确实您认为 + opreator的作用是什么;无论原始符号如何,它都会使值为正。

The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.

var a =-4;
a = Math.abs(a); // 4

执行 + a 实际上是与做 a * 1 相同;如果需要,它会将 a 中的值转换为数字,但之后不会更改该值。

Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

var a = "5";
a = +a; // 5

使用 + 运算符有时将字符串转换为数字,但你有 parseInt parseFloat 函数以更具体的方式进行转换。

The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.

var a = "5";
a = parseInt(a, 10); //5

这篇关于在javascript中解释+ var和-var一元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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