简体   繁体   English

基于自动分号插入JS规则的有趣错误。 需要说明

[英]Interesting error based on automatic semicolon insertion JS rules. Explanation required

Today I wrote code for some programming contest. 今天,我为一些编程比赛编写了代码。 When I run it I was surprised because of error. 当我运行它时,我因错误而感到惊讶。 Cannot read property 'forEach' of undefined in a place where looks like "error free space". 无法在看起来像“无错误空间”的位置读取未定义的属性“ forEach ”。

sum = 0
            [-1,0,1].forEach(deltar =>{...});

When I add semicolon after sum variable value assignment code start to works. 当我在sum变量值赋值代码开始添加分号后开始工作。

sum = 0;
            [-1,0,1].forEach(deltar =>{...});

It's very curious about JS behavior what do interpreter mismatch here? JS行为非常好奇,这里的解释器不匹配是什么? how do JS mess with integer and array after it? JS如何将整数数组弄乱呢?

Here it is a full code of the function to make the complete picture of variables declaration. 这是制作变量声明的完整图片的完整函数代码。

function boxBlur(img) {
    let [h,w] = [img.length-1,img[0].length-1];
    let [answer,sum,tmp] = [[],0,[]]
    for(let row = 1; row < h; row += 1){
        tmp = []
        for(let clmn = 1; clmn < w; clmn += 1){
            sum = 0;
            [-1,0,1].forEach(deltar =>{
                [-1,0,1].forEach(deltac =>{
                    sum += img[row+deltar][clmn+deltac]
                });
            });
            tmp.push(parseInt(sum/9));
        }
        answer.push(tmp);
    }
    return answer;
}

The problem is that when you don't put a semi-colon it doesn't automatically put ; 问题是,当您不放置分号时,它不会自动放置; instead 代替

  • it tries to get the property 3 of a number. 它尝试获取数字的属性3
  • Here [1,2,3] doesnot work as array but as Bracket Notation . 在这里[1,2,3]作为数组,但是可以用作括号符号
  • Due to Comma Operator the last operand 3 . 由于逗号运算符 ,最后一个操作数3
  • So the 0[3] is undefined . 因此0[3]undefined undefined.forEach(){...} will obviously throw error. undefined.forEach(){...}显然会引发错误。

 let sum = 0 [1,2,3] console.log(sum) 

1,2,3 === 3 

comma operator 逗号运算符

so 所以

[1,2,3] -> [3] i.e. is property named 3 

bracket notation 括号符号

therefore 因此

sum = 0[3] is undefined - 

since the Number(0) has no property called 3 因为Number(0)没有称为3的属性

to illustrate further 进一步说明

 var sum = 0 [1,2,3,'constructor'] console.log(sum); 

now the code is equivalent to 现在的代码相当于

var sum = 0['constructor']

or 要么

var sum = 0..constructor

which, as you see in the console is the Number object constructor 正如您在控制台中看到的那样,它是Number对象的构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM