基于自动分号插入JS规则的有趣错误.需要说明 [英] Interesting error based on automatic semicolon insertion JS rules. Explanation required

查看:26
本文介绍了基于自动分号插入JS规则的有趣错误.需要说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我为一些编程比赛写了代码.当我运行它时,我因错误而感到惊讶.在看起来像无错误空间"的地方无法读取未定义的属性"forEach" .

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".

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

当在 sum 变量值赋值代码开始起作用后添加分号时.

When I add semicolon after sum variable value assignment code start to works.

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

对于 JS 的行为很好奇,这里的解释器不匹配是什么? JS 如何与整数 array 混淆?

It's very curious about JS behavior what do interpreter mismatch here? how do JS mess with integer and array after it?

这里是完整的变量声明代码功能的完整代码.

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;
}

推荐答案

1,2,3 === 3 

逗号运算符

如此

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

方括号

因此

sum = 0[3] is undefined - 

因为Number(0)没有称为3的属性

since the Number(0) has no property called 3

以进一步说明

var sum = 0
[1,2,3,'constructor']

console.log(sum);

现在代码等同于

var sum = 0['constructor']

var sum = 0..constructor

在控制台中看到的是 Number 对象构造函数

which, as you see in the console is the Number object constructor

这篇关于基于自动分号插入JS规则的有趣错误.需要说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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