


Summary 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:
var car = new Object();
car.colour = 'red';
car. wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;
The following writing can achieve the same effect:
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:
var moviesThatNeedBetterWriters = new Array(
'Transformers','Transformers2','Avatar','Indiana Jones 4'
);
More The concise way to write it is:
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:
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:
var direction;
if(x direction = 1;
} else {
direction = -1;
}
We can use the following code to replace this writing:
(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:
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:
<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:
var numbers = [3,342,23,22,124];
var max = 0;
for (var i=0;i
max = numbers[i];
}
}
alert(max);
In fact, the same function can be achieved without looping:
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:
You can even use Math.max to detect which properties the browser supports:
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:
function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;
And a more elegant way of writing is:
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:
Great Web resources
- Sitepoint
-
A List Apart li>
- YUI Blog
- Blame it on the voices
- Oddly specific a>
< ;li>Opera Web Standards Curriculum
스크립트는 다음과 같습니다.
// 클래식 이벤트 처리 예제
(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 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는 표준에 대한 지원이 가장 낮기 때문입니다. 최종 사용자가 보는 결과는 작성한 코드가 특정 브라우저에서 올바르게 실행되지 않을 수 있다는 것입니다. 모든 주요 브라우저에서 코드를 테스트해야 합니다. 이 작업은 시간이 많이 걸릴 수 있지만 완료되어야 합니다.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor