Why does 'string'[0] behave differently on

2019-04-12 03:02发布

问题:

Consider the following Html file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>test</title>
        <style type="text/css">

        </style>
    </head>
    <body>
        <script type="text/javascript">
            alert('' +
                '\'test\'[0] = \'' + 'test'[0] + '\'\n' +
                '\'test\'.charAt(0) = \'' + 'test'.charAt(0) + '\'\n'
            );
        </script>
    </body>
</html>

When I open this file on my local machine it gives the following output (both in ie8 and Chrome):

'test'[0] = 't'
'test'.charAt(0) = 't'

When I host this file on IIS7.5 I still get the same result in Chrome but ie8 gives the following result:

'test'[0] = 'undefined'
'test'.charAt(0) = 't'

How is this possible?

回答1:

Jan, just to add to your own answer, the more standards compliant way to enable compatibility view would be to just use a standard doctype at the beginning of your document.

<!DOCTYPE html>

Which is the HTML5 doctype, should put you into standards mode as well.



回答2:

OK I found out it was due to compatibility view. Internet explorer comes standard (I think, I am not the owner of this laptop) with the option to display all intranet pages in compatibility View. To force it to use ie8 compatibility view I had to add the following meta tag to the head element:

<meta http-equiv="X-UA-Compatible" content="IE=edge" > <!-- IE8 mode -->

You can also turn this option off under 'Page' > 'Compatibility View Settings'

This question has put me in the right direction.

EDIT: I advise web developers to leave this option checked in ie8, because most of your users will have it checked. This way you will catch these errors in the development cycle.

EDIT2: sv_in is right. IE=edge is much cleaner.