Solve common problems in your JavaScript code - Learn web development 编辑

The following links point to solutions to common problems you may encounter when writing JavaScript.

Common beginner's mistakes

Correct spelling and casing

If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly.

Some common built-in browser functions that cause problems are:

CorrectWrong
getElementsByTagName()getElementbyTagName()
getElementsByName()getElementByName()
getElementsByClassName()getElementByClassName()
getElementById()getElementsById()

Semi-colon position

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

CorrectWrong
elem.style.color = 'red';elem.style.color = 'red;'

Functions

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 with the following statement:

myFunction();

Function scope

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 from the function.

Running code after a return statement

Remember also that when you return from a function, the JavaScript interpreter exits the function — no code 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".

Object notation versus normal assignment

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

const myNumber = 0;

With Objects, however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. For example:

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

Basic definitions

Basic use cases

General

Variables

Math

Strings

Arrays

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

Intermediate use cases

Functions

Objects

JSON

Events

Object-oriented JavaScript

Web APIs

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:88 次

字数:18091

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文