Javascript 无法设置未定义的属性... --- 很奇怪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4197404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:19:55  来源:igfitidea点击:

Cannot Set Property ... of undefined --- bizarre

javascriptgoogle-chrome

提问by rvandervort

I'm getting a bizarre error in Chrome... check out the screenshot below.

我在 Chrome 中遇到一个奇怪的错误...查看下面的屏幕截图。

I define record using object literal syntax.

我使用对象字面量语法定义记录。

I try setting the "id" property and get the exception.

我尝试设置“id”属性并获得异常。

I've tried both :

我都试过:

record['id'] = 'wtf';

and also

并且

record.id = 'wtf';

I use this type of syntax all over the place in my script.... what could be going on here ? Is this a bug in Chrome ?

我在我的脚本中到处使用这种类型的语法......这里会发生什么?这是 Chrome 中的错误吗?

alt text

替代文字

EDIT : I've solved the problem for now, but I'm still not sure why this is happening. I moved the definition of record to occur outside of the if block. Anyone know what could be occurring ? I thought all variable declarations were scoped to the function and therefore this shouldn't be an issue.

编辑:我现在已经解决了这个问题,但我仍然不确定为什么会这样。我将记录的定义移动到 if 块之外。有谁知道会发生什么?我认为所有变量声明的范围都在函数内,因此这应该不是问题。

回答by Matthew Crumley

The problem is most likely that dlis less than or equal to zero, so the statement that initializes recorddoesn't get executed. From your indentation, it looks like you intended for both statements to be part of the ifblock, but with no braces, the record['id'] = 'wtf';statement gets executed no matter what.

问题很可能dl小于或等于零,因此初始化的语句record不会被执行。从您的缩进来看,您似乎打算将两个语句都作为if块的一部分,但是没有大括号,record['id'] = 'wtf';无论如何都会执行该语句。

By moving the variable initialization outside the if statement, you forced it to happen in any case and moved the assignment inside the if block (which, I'm assuming is what you wanted).

通过将变量初始化移到 if 语句之外,你强迫它在任何情况下发生并将赋值移到 if 块中(我假设这是你想要的)。

Probably a better way to solve it is adding braces like this:

可能更好的解决方法是添加这样的大括号:

if (dl > 0) {
    var record = {};

    record.id = 'wtf';
}

Unless you really do want to initialize recordin both cases.

除非你真的想record在这两种情况下都初始化。

You are correct about variable declarationsbeing scoped to the function, but the assignmentdoesn't happen until you get to that point in the code. recordwas in scope, but it still had its default value of undefinedbecause you hadn't assigned anything to it yet.

您对作用域为函数的变量声明是正确的,但是直到您到达代码中的那个点时才会进行赋值record是在范围内,但它仍然有它的默认值,undefined因为你还没有给它分配任何东西。

回答by meder omuraliev

Works for me, no reason it shouldn't work. Are you sure it's referring to that exact line? what if you alert(record)before you set it? Have you tried to debug it yet?

对我有用,没有理由它不应该工作。你确定它指的是那条确切的线吗?如果你alert(record)在设置之前呢?你试过调试吗?