google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






10 thủ thuật JavaScript đơn giản nên nắm vững Trong bài viết hướng dẫn thực hành JavaScript này, tác giả sẽ cung cấp cho 10 thủ thuật JavaScript đơn giản mà bạn nên nắm vững để làm việc với ngôn ngữ JavaScript lập trình hiệu quả hơn.


Nhãn: 10, thủ thuật JavaScript, nắm vững, ngôn ngữ JavaScript, ngôn ngữ lập trình

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:

// BAD: This will cause an error in code when foo is undefined
if (foo) {
	doSomething();
} 

// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
	doSomething();
}

// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
	doSomething();
}

However, there may be situations, when we have deeper structure and proper checking would look like this:

// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
	doSomething();
}

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:

function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}

doSomething('', 'foo', 5, [], false);

It's always easier to pass only one object instead of several arguments:

function doSomething() {
	// Leaves the function if nothing is passed
	if (!arguments[0]) {
		return false;
	}

	var oArgs	= arguments[0]
		arg0	= oArgs.arg0 || "",
		arg1	= oArgs.arg1 || "",
		arg2	= oArgs.arg2 || 0,
		arg3	= oArgs.arg3 || [],
		arg4	= oArgs.arg4 || false;
}

doSomething({
	arg1	: "foo",
	arg2	: 5,
	arg4	: false
});

This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:

function createList() {
	var aLI	= ["first item", "second item", "third item",
		"fourth item", "fith item"];

	// Creates the fragment
	var oFrag	= document.createDocumentFragment();

	while (aLI.length) {
		var oLI	= document.createElement("li");

		// Removes the first item from array and appends it
		// as a text node to LI element
		oLI.appendChild(document.createTextNode(aLI.shift()));
		oFrag.appendChild(oLI);
	}

	document.getElementById('myUL').appendChild(oFrag);
}

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace().

Following example is a rough implementation of making a more verbose output from a single deal in online poker:

var sFlop	= "Flop: [Ah] [Ks] [7c]";
var aValues	= {"A":"Ace","K":"King",7:"Seven"};
var aSuits	= {"h":"Hearts","s":"Spades",
			"d":"Diamonds","c":"Clubs"};

sFlop	= sFlop.replace(/\[\w+\]/gi, function(match) {
	match	= match.replace(match[2], aSuits[match[2]]);
	match	= match.replace(match[1], aValues[match[1]] +" of ");

	return match;
});

// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:

outerloop:
for (var iI=0;iI<5;iI++) {
	if (somethingIsTrue()) {
		// Breaks the outer loop iteration
		break outerloop;
	}

	innerloop:
	for (var iA=0;iA<5;iA++) {
		if (somethingElseIsTrue()) {
			// Breaks the inner loop iteration
			break innerloop;
		}

	}
}

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript.

And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web