pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-CN/docs/Learn_web_development/Howto/Solve_JavaScript_problems

ntent="https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Howto/Solve_JavaScript_problems" />

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

解决 JavaSctript 代码的常见问题

以下链接指向撰写 JavaScript 代码时可能遇见的问题。

初学者常见的错误

正确的拼写和使用

如果你的代码不工作或浏览器抱怨某些东西是未定义的,请检查你是否正确拼写了所有的变量名称,函数名称等。

导致问题的一些常见的内置浏览器函数有:

正确 错误
getElementsByTagName() getElementbyTagName()
getElementsByName() getElementByName()
getElementsByClassName() getElementByClassName()
getElementById() getElementsById()

分号的位置

必须确保没有错误地放置分号,例如:

正确 错误
elem.style.color = 'red'; elem.style.color = 'red;'

函数

函数有很多容易出错的地方。

最常见的错误之一是函数被声明了却没有被调用。例如:

js
function myFunction() {
  alert("This is my function.");
}

这个函数不会执行,除非你调用它,例如:

js
myFunction();

函数作用域

记住,函数拥有自己的作用域——你不能从函数外部访问一个函数内的变量值,除非你在全局声明了该变量(即不在任何函数内),或者从函数外部获得它的返回值

在 return 语句之后运行代码

还要记住,当你向一个函数外部返回一个值时,JavaScript 解释器会退出这个函数——在 return 语句之后,不会执行任何代码。

事实上,如果你在返回语句之后有代码,某些浏览器(如 Firefox)会在开发人员控制台中显示出一条错误消息。Firefox 在返回语句后会给你“无法运行到的代码”的提示。

对象标记法与正常赋值

当你在 JavaScript 中正常赋值时,使用等号:

js
const myNumber = 0;

但是在对象中,需要小心地使用正确的语法标签。你需要使用花括号来包裹一个对象,冒号来分隔成员名称和值,并用逗号来分隔每个成员,例如:

js
const myObject = {
  name: "Chris",
  age: 38,
};

基本定义

基本用例

常见

变量

数学

字符串

数组

JavaScript 调试

有关 JavaScript 调试的更多内容,请查阅处理 JavaScript 常见问题页面,也可以查看其他常见错误的描述。

在代码中作出判断

循环/迭代

中级用例

函数

对象

JSON

事件

面向对象的 JavaScript

Web API

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy