正在翻譯中。


以下鏈接針對您需要修復的常見問題的解決方案,以便讓您的JavaScript語法正確執行。

初學者常見的錯誤

糾正語法和代碼


 

如果您的代碼毫無反映或瀏覽器反饋某些內容「未定義」,請檢查您是否「正確輸入」所有變量名稱,函數名稱等。

以下的常見造成問題的內置瀏覽器功能比對:

 

正確  錯誤 
getElementsByTagName() getElementbyTagName()
getElementsByName() getElementByName()
getElementsByClassName() getElementByClassName()
getElementById() getElementsById()

分號位置

You need to make sure you don't place any semi-colons incorrectly. For example:

Correct Wrong
elem.style.color = 'red'; elem.style.color = 'red;'

功能內容

There are a number of things that can go wrong with functions.

One of the most common errors is to declare the function, but not call it anywhere. For example:

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

This code won't do anything unless you call it, for example with

myFunction();

功能範圍

Remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value out of the function.

在return語句後執行語法

Remember also that when you return a value out of a function, the JavaScript interpreter exits the function — no code declared after the return statement will run.

In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement".

對象表示法與正確的指派

When you assign something normally in JavaScript, you use a single equals sign, e.g.:

const myNumber = 0;

This doesn't work in Objects, however — with objects you need to separate member names from their values using colons, and separate each member with a comma, for example:

const myObject = {
  name: 'Chris',
  age: 38
}

基本定義

基本使用例子

序列

Debugging JavaScript

For more information on JavaScript debugging, see Handling common JavaScript problems; also see Other common errors for a description of common errors.

Making decisions in code

Looping/iteration

進階使用例子

文件標籤與貢獻者

此頁面的貢獻者: mdnwebdocs-bot, DoJQuadArts
最近更新: mdnwebdocs-bot,