var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
document.write(arr[x]);//9
//为什么js会忽略括号外的减号?为什么9不是4?
答案 0 :(得分:2)
在评估此语句后,此(++x)-1
将导致0并且x
将为1,因为您已将其递增1并为其指定值0。
因此arr[x]
(在语句document.write(arr[x]);
中)实际上是arr[1]
而arr[1]
的值是9。
关于作业:
arr[x] = (++x)-1;
现在,数组的第一个元素(索引为0)的值将被赋值为0.这就是为什么如果打印arr,您将获得以下输出:
[0,9,2]
答案 1 :(得分:1)
你写信给
arr[x] // which is arr[0]
(++x)-1; // 1-1 = 0, x = 1
然后你写出
document.write(arr[x]); //arr[1] which is 9
为什么js会忽略括号外的减号?
所以不,js不会忽略减号。也许尝试使用数组来理解前缀++
运算符wtthout,因为在这种情况下他们会让你感到困惑。
示例:
var x = 0, y = 0;
y = (++x) - 1;
document.write("x: " +x + " y: " y); //x == 1, y == 0
答案 2 :(得分:0)
答案 3 :(得分:0)
arr[0] = 0
,此处x
递增1,x
= 1,(1)-1 = 0
arr[1]
将打印9,因为x
= 1,您正在访问该数组 索引为1的元素
document.write(arr)
它将打印[0,9,2]
,因为第一个 数组的元素(索引为0)将被赋值为0。
var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
// x would be 1 after the evaluation of this statement.
//document.write(x);// it will print 1
document.write(arr[x]);// arr[1] it will print 9
//document.write(arr);// it will print [0,9,2]