search
HomeWeb Front-endJS TutorialSummary of seven details that JavaScript beginners should pay attention to_javascript skills

Each language has its own special features. For JavaScript, you can use var to declare variables of any type. This scripting language seems very simple, but writing elegant code requires continuous accumulation of experience. This article lists seven details that JavaScript beginners should pay attention to and share them with you.
(1) Simplify the code
It is very simple to define objects and arrays in JavaScript. We want to create an object, which is usually written like this:

Copy code The code is as follows:

var car = new Object();
car.colour = 'red';
car. wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;

The following writing can achieve the same effect:
Copy code The code is as follows:

var car = {
colour:'red',
wheels:4,
 hubcaps:'spinning',
 age:4
}

The following is much shorter, and you don't need to write the object name repeatedly.
In addition, there is also a concise way to write arrays. In the past, we declared arrays as follows:
Copy code The code is as follows:

var moviesThatNeedBetterWriters = new Array(
'Transformers','Transformers2','Avatar','Indiana Jones 4'
);

More The concise way to write it is:
Copy the code The code is as follows:

var moviesThatNeedBetterWriters = [
'Transformers','Transformers2','Avatar','Indiana Jones 4'
];

For arrays, there is a special thing like associative arrays. You will find that a lot of code defines objects like this:
Copy the code The code is as follows:

var car = new Array();
car['colour'] = 'red';
car['wheels'] = 4;
car['hubcaps'] = 'spinning';
car['age'] = 4;

This is crazy, don't get confused, "associative array" is just an alias for an object.
Another way to simplify the code is to use the ternary operator, for example:
Copy the code The code is as follows:

var direction;
if(x direction = 1;
} else {
direction = -1;
}

We can use the following code to replace this writing:
Copy the code The code is as follows:
var direction = x
(2) Use JSON as data format
The great Douglas Crockford invented the JSON data format to store data , you can use native javascript methods to store complex data without any additional conversion, for example:
Copy code The code is as follows:

var band = {
"name":"The Red Hot Chili Peppers",
"members":[
{
"name": "Anthony Kiedis",
"role":"lead vocals"
},
{
"name":"Michael 'Flea' Balzary",
"role":"bass guitar , trumpet, backing vocals"
},
{
"name":"Chad Smith",
"role":"drums,percussion"
},
{
"name":"John Frusciante",
"role":"Lead Guitar"
}
],
"year":"2009"
}

You can use JSON directly in JavaScript, or even as a format returned by API, which is used in many APIs, such as:
Copy code The code is as follows:

<script> <BR>function delicious(o){ <BR>var out = '<ul>'; <BR> for(var i=0;i<o.length;i ){ <BR>out = '<li><a href="' o[i].u '">' <BR>o[i ].d ''; <BR>} <BR>out = ''; <BR>document.getElementById('delicious').innerHTML = out; <BR>} <BR></script>
> ;

Here calls delicious's web service to get the latest bookmarks, returns them in JSON format, and then displays them in an unordered list.
Essentially, JSON is the most lightweight way for describing complex data, and it runs directly in the browser. You can even use it by calling the json_decode() function in PHP.
(3) Try to use JavaScript native functions
To find the maximum number in a set of numbers, we may write a loop, for example:
Copy code The code is as follows:

var numbers = [3,342,23,22,124];
var max = 0;
for (var i=0;iif(numbers[i] > max){
max = numbers[i];
}
}
alert(max);

In fact, the same function can be achieved without looping:
Copy code The code is as follows:

var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers [0]);

The simplest way to write it is:
Copy code The code is as follows:
Math.max(12,123,3,2,433,4); // returns 433

You can even use Math.max to detect which properties the browser supports:
Copy code The code is as follows:

var scrollTop= Math.max(
doc.documentElement.scrollTop,
doc.body.scrollTop
);

If you want to add a class style to an element, the original writing may be like this:
Copy code The code is as follows:

function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;

And a more elegant way of writing is:
Copy code The code is as follows:

function addclass(elm,newclass){
var classes = elm.className.split(' ');
classes. push(newclass);
elm.className = classes.join(' ');
}

(4) Event delegate
event is JavaScript Very important part. We want to bind click events to links in a list. The general approach is to write a loop and bind events to each link object. The HTML code is as follows:
Copy Code The code is as follows:

스크립트는 다음과 같습니다.
코드 복사 코드는 다음과 같습니다.

// 클래식 이벤트 처리 예제
(function(){
var resources = document.getElementById('resources');
varlinks = resources.getElementsByTagName('a');
var all = links.length;
for(var i=0;i// 각 링크에 리스너 연결
links[i].addEventListener('click',handler,false) ;
};
function handler(e){
var x = e.target; // 클릭한 링크 가져오기
alert(x)
e.preventDefault();
};
})();

이벤트를 목록의 상위 개체에만 바인딩하는 것이 더 합리적입니다.
코드 복사 코드는 다음과 같습니다.

(function(){
var resources = document.getElementById('resources');
resources.addEventListener(' click',handler,false);
function handler(e){
var x = e.target;
if(x.nodeName.toLowerCase() === 'a '){
alert('이벤트 위임:' x)
e.preventDefault()
}
} ;
})();

(5) 익명 함수
JavaScript에서 가장 짜증나는 점 중 하나는 변수에 특정 범위가 없다는 것입니다. 일반적으로 모든 변수, 함수, 배열 또는 객체는 전역적이므로 동일한 페이지의 다른 스크립트가 이에 액세스하고 덮어쓸 수 있습니다. 해결책은 변수를 익명 함수로 캡슐화하는 것입니다. 예를 들어, 다음 정의는 세 개의 전역 변수와 두 개의 전역 함수를 생성합니다.
코드 복사 코드는 다음과 같습니다.

var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [.. ]
}
function getMemberDetails(){
// [...]
}

캡슐화하면 다음과 같습니다.
코드 복사 코드는 다음과 같습니다.

var myApplication = function(){
var name = ' 크리스';
var age = '34';
var status = 'single';
return{
createMember:function(){
// [...]
},
getMemberDetails:function (){
// [...]
}
}
}()
// myApplication.createMember() 및
// myApplication.getMemberDetails()가 이제 작동합니다.

이것은 JavaScript 디자인 패턴의 일종인 싱글톤 모드입니다. 이 모드는 YUI에서 많이 사용됩니다. 🎜>
코드 복사 코드는 다음과 같습니다.
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single'
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
return{
create:createMember,
get:getMemberDetails
}
}();
//myApplication.get( ) 및 myApplication.create()가 이제 작동합니다.


(6) 코드 구성 가능
작성한 코드를 원하는 경우 다른 사람이 더 쉽게 사용하거나 수정할 수 있도록 하려면 구성 가능해야 합니다. 해결 방법은 작성한 스크립트에 구성 개체를 추가하는 것입니다. 핵심 사항은 다음과 같습니다.
1. 스크립트에 구성이라는 개체를 추가합니다.
2. CSS ID, 클래스 이름, 언어 등 다른 사람이 변경하고 싶어할 수 있는 모든 항목을 구성 개체에 저장합니다.
3. 다른 사람이 재정의할 수 있도록 이 객체를 공용 속성으로 반환합니다.

(7) 코드 호환성 호환성은 초보자들이 간과하기 쉬운 부분인데, 보통 자바스크립트를 배울 때 고정된 브라우저에서 테스트를 하는데, 이 브라우저가 그럴 가능성이 매우 높습니다. IE는 매우 치명적입니다. 현재 주요 주류 브라우저 중 IE는 표준에 대한 지원이 가장 낮기 때문입니다. 최종 사용자가 보는 결과는 작성한 코드가 특정 브라우저에서 올바르게 실행되지 않을 수 있다는 것입니다. 모든 주요 브라우저에서 코드를 테스트해야 합니다. 이 작업은 시간이 많이 걸릴 수 있지만 완료되어야 합니다.
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools