块语句
确保您的变量位于范围的顶部(或将其分配给窗口),然后它就可以从 devtools 访问。此外,请确保对函数执行相同的操作。我会遇到的一个问题是我无法从window.onload 内部访问这些函数。例如,
let jack = 'I am jack!';
{
let jill = 'I am jill!';
}
console.log(jack); //=> 'I am jack!'
console.log(jill); //=> Uncaught ReferenceError: jill is not defined
或
window.onload = function() {
let jack = 'I am jack!'
let jill = 'I am jill!'
}
console.log(jack); //=> Uncaught ReferenceError: jack is not defined
console.log(jill); //=> Uncaught ReferenceError: jill is not defined
但是,如果我想在区块外访问jack 或jill 怎么办?
let jill;
let jack = 'I am jack!';
{
jill = 'I am jill!';
}
console.log(jack); //=> 'I am jack!'
console.log(jill); //=> 'I am jill!'
或
let jack = 'I am jack!';
{
window.jill = 'I am jill!';
}
console.log(jack); //=> 'I am jack!'
console.log(jill); //=> 'I am jill!'
当然,上面的将jill 词法绑定到字符串'I am jill!',而下面的只是将其分配为window 的属性。
其他疑难解答
确保您的脚本文件index.js 正确包含在文件index.html 中也很重要。例如,
<script src='index.js'></script>
或
<script src='./index.js'></script>
确保type 属性等于module 或text/javascript 或根本不包括在内。如果您想在执行脚本之前等待页面加载,请将defer 添加到标签中:
<!-- Deferred Script -->
<script src='./index.js' defer></script>
<!-- Module Script -->
<script src='./index.js' type='module'></script>
<!-- Normal Script -->
<script src='./index.js' type='text/javascript'></script>
<!-- Incorrect Script -->
<script src='./index.js' type='text/plain'></script>
<!-- Incorrect Script -->
<script src='./index.js' type='blah'></script>
旁注
希望我的回答对您有所帮助,从而解决问题。