简体   繁体   English

当对象具有“new”作为属性名称时,来自IE8和IE7的“预期标识符”错误

[英]“Expected identifier” error from IE8 and IE7 when object has “new” as property name

I have a web page that I am testing in IE8, and it is telling me that the page has errors. 我有一个我在IE8中测试的网页,它告诉我该页面有错误。 I tried to come up with a simple example and I came up with this: 我试图想出一个简单的例子,我想出了这个:

<!DOCTYPE HTML>
<html>
<head>
  <script>
  var stuff = {
    "foo": {
      "new": 42
    }
  };
  var thing = stuff.foo.new;
  </script>
</head>
<body>
</body>
</html>

It can be tested here . 它可以在这里测试。

This is the error I see: 这是我看到的错误:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Timestamp: Mon, 21 Jan 2013 23:11:52 UTC


Message: Expected identifier
Line: 11
Char: 25
Code: 0
URI: file:///C:/Documents%20and%20Settings/Administrator/My%20Documents/ie8PropertyNameTest.html

IE7 shows a similar error. IE7显示了类似的错误。 It works fine in every other browser I tested the page in, including newer versions of IE. 它在我测试页面的每个其他浏览器中都可以正常工作,包括新版本的IE。 Does anyone know what is causing this problem and how to avoid it (other than the obvious solution of picking some other name)? 有谁知道导致这个问题的原因以及如何避免它(除了选择其他名称的明显解决方案)?

new is a JavaScript reserved word. new是一个JavaScript保留字。 You can get to the property with: 您可以通过以下方式前往酒店:

var thing = stuff.foo["new"];

(I'll wager). (我打赌)。 You'll save yourself some trouble by calling the property something like "isNew". 你可以通过调用属性“isNew”来省去一些麻烦。

If you use new as a key, don't do this: 如果您使用new作为键,请不要这样做:

foo.new = 'bar';

Instead, do this: 相反,这样做:

foo['new'] = 'bar';

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

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