JavaScript数组解构分配产生奇怪的错误 [英] Javascript array destructuring assignment gives strange errors

查看:72
本文介绍了JavaScript数组解构分配产生奇怪的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Javascript解构分配时,我刚刚注意到一个奇怪的错误,这使我不得不做出一些猜测.我在这里发布,以便我可以展示我学到的东西.(我接受 JavaScript自动分号插入(ASI)的规则是什么?,但是我的问题是,当ASI的工作方式与我预期的不同时,如何诊断一个奇怪的错误;这是我希望能在何时找到的答案搜索数组解构错误"或类似内容.)

I've just noticed a strange error when using Javascript destructuring assignment, which took me some guesswork to resolve. I'm posting here so I can show what I learned. (I accept that the question about Javascript semicolon insertion is answered by What are the rules for JavaScript's automatic semicolon insertion (ASI)?, but my problem was about how to diagnose a strange error when ASI works differently than I was expecting; it's an answer that I would have hoped to find when searching for "array destructuring error" or similar.)

以下代码:

let next_col_time_step = head_steps.reduce(
    choose_next_step, [-1, -1, null]
    )
[next_step_col, next_step_time, next_step] = next_col_time_step

运行时会产生一个非常混乱的错误:

When run generates an very confusing error:

ReferenceError: can't access lexical declaration 'next_col_time_step' before initialization

尽管(显然)只是在错误行之前被初始化.

Despite (apparently) having been just initialized before the error line.

或者,如果我尝试查看已分配的值,则:

Or, if I try to see what value has been assigned, thus:

let next_col_time_step = head_steps.reduce(
    choose_next_step, [-1, -1, null]
    )
console.log("next_col_time_step %s", next_col_time_step)
[next_step_col, next_step_time, next_step] = next_col_time_step

我看到显示的期望值和另一个错误:

I see the expected value displayed and a different error:

next_col_time_step 2,52,[object Object] 
TypeError: console.log(...) is undefined

console.log(...)显然可以按预期工作,然后报告为未定义.这是怎么回事?

I.e., console.log(...) apparently works as expected, then is reported as undefined. What's going on here?

推荐答案

这里的问题是Javascript语法中令人困惑的歧义.

The problem here is a confusing ambiguity in Javascript syntax.

是否注意到我没有使用; 语句终止符?

Notice that I wasn't using ; statement terminators?

似乎数组解构分配被解析为应用于上一条语句的数组索引操作.

It appears that the array destructuring assignment is being parsed as an array indexing operation applied to the previous statement.

快速解决方案:在前面的语句之后添加; (尽管不幸的是,如果通常省略这些样式,则会强制产生不一致的样式):

Quick fix: add ; after the preceding statement (though this unfortunately forces an inconsistent style if these are generally omitted):

let next_col_time_step = head_steps.reduce(
    choose_next_step, [-1, -1, null]
    );
[next_step_col, next_step_time, next_step] = next_col_time_step

然后,瞧!,一切都很好:)

And, voila!, all is well :)

这篇关于JavaScript数组解构分配产生奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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