gpt4 book ai didi

vue.js - forEach()调用无法编译

转载 作者:行者123 更新时间:2023-12-02 10:53:28 24 4
gpt4 key购买 nike

以下代码部分可以使用Vue CLI 2正确编译,但是在我的Nuxt项目中却不能:

// Populate row with times + total of times at the end of the row
let total = 0
['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'].forEach(day => {
const temp = weekTimes.find(x => x.date === this[day])
if (temp) {
this[day + 'Time'] = temp.hours
total += parseInt(temp.hours)
} else {
this[day + 'Time'] = ''
}
})

第三行( ['mon', 'tue'...)与以下编译错误相关联:

Expected indentation of 12 spaces but found 10 Unexpected newline between object and [ of property access

Unexpected use of comma operator

Expected parentheses around arrow function argument having a body with curly braces



但是它是有效的ES6代码,那么为什么编译器对此有问题?

最佳答案

省略分号的危险。

这个:

let total = 0
['mon', 'tue'].forEach(day => {

将被视为:

let total = 0['mon', 'tue'].forEach(day => {
0[...]部分将被视为尝试访问值 0上的属性。尝试在浏览器控制台中运行以下示例:

0['toFixed'](2)

这只是通过参数2调用 toFixed值上的 0方法的一种方法。

错误的逗号运算符部分指的是 'mon', 'tue'部分。尝试在控制台中输入以下内容:

'mon', 'tue'

尽管很少使用像这样的逗号运算符,但您应该发现它的运算结果为最后一个值,因此在这种情况下为 'tue'。因此,使用我之前的示例,它有点像这样:

0['toString', 'toFixed'](2)

在这里 toString实际上被忽略了,它像我之前的示例一样仅调用 toFixed。 Linters将检查逗号的这种用法,因为它们几乎总是由错误解释的逗号引起的。与您的情况一样,通常将其用作数组中的定界符,而不是逗号运算符。

回到您的代码,这是:

let total = 0
['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'].forEach(day => {

将尝试访问值 'sun'0属性,该属性将为 undefined。然后它将尝试在 forEach上调用 undefined方法,这将引发错误。

因此,尽管您的代码有效,但它不会表现出预期的行为。短毛绒正在发现这些错误,并试图帮助您解决它们。

最简单的解决方案是插入分号。

此警告:

Expected parentheses around arrow function argument having a body with curly braces



只是一条小规则。它期望您将 .forEach(day => {编写为 .forEach((day) => {。从正确性的 Angular 来看,代码没有错,这实际上只是强加了代码样式首选项的轻巧。

关于vue.js - forEach()调用无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com