Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Tips to improve JavaScript efficiency

  sonic0002        2013-07-27 20:50:40       5,703        1    

Writing JavaScript code is tedious and error prone. You not only need to implement the necessary functions, but also need to ensure cross browser compatibility. This often causes the low efficiency of JavaScript developers. Here we recommend 12 tips you can benefit from.

1. Remove array element by index

If we want to remove one element in an array, we can use splice.

function removeByIndex(arr, index) {
    arr.splice(index, 1);
}
test = new Array();
test[0] = ’Apple’;
test[1] = ’Ball’;
test[2] = ’Cat’;
test[3] = ’Dog’;
alert(“Array before removing elements: ”+test);
removeByIndex(test, 2);
alert(“Array after removing elements: ”+test);

The output is : Apple,Ball,Dog

2. Remove array element b value

There is no remove method in JavaScript, so we have to implement the remove method ourselves.

function removeByValue(arr, val) {
	for(var i=0; i<arr.length; i++) {
		if(arr[i] == val) {
			arr.splice(i, 1);
			break;
		}
	}
}
var somearray = ["mon", "tue", "wed", "thur"]
removeByValue(somearray, ”tue”);
//somearray now contains  ”mon”, ”wed”, ”thur”

One better way is to use prototype to implement this method:

Array.prototype.removeByValue = function(val) {
	for(var i=0; i<this.length; i++) {
		if(this[i] == val) {
			this.splice(i, 1);
			break;
		}
	}
}
//..
var somearray = ["mon", "tue", "wed", "thur"]
somearray.removeByValue(“tue”);

3. Dynamically call one method with specified string

Sometimes we may need to call some existing method dynamically at runtime. How can this be achieved?

var strFun = ”someFunction”; //someFunction is some existing function name
var strParam = ”this is the parameter”; //Parameters to be passed
var fn = window[strFun];
//call the function.
fn(strParam);

4. Generate random numbers between 1 and N

var random = Math.floor(Math.random() * N + 1);
//Random number between 1 and 10
var random = Math.floor(Math.random() * 10 + 1);
//Random number between 1 and 100
var random = Math.floor(Math.random() * 100 + 1);

5. Capture the close event of web browser

We often need to remind the user that some data is not saved when they close the browser window.

<script language=”javascript”>
function fnUnloadHandler() {
alert(“Unload event.. Do something to invalidate users session..”);
}
</script>
<body onbeforeunload=”fnUnloadHandler()”>
………
</body>

6. Check whether form data is changed

Sometimes we need to check whether the user modifies some data in the form. We can use below method. If the data is changed, then it should return true, otherwise it should return false.

function formIsDirty(form) {
	for (var i = 0; i < form.elements.length; i++) {
		var element = form.elements[i];
		var type = element.type;
		if (type == ”checkbox” || type == ”radio”) {
			if (element.checked != element.defaultChecked) {
				return true;
			}
		}
		else if (type == ”hidden” || type == ”password” ||
			type == ”text” || type == ”textarea”) {
			if (element.value != element.defaultValue) {
				return true;
			}
		}
		else if (type == ”select-one” || type == ”select-multiple”) {
			for (var j = 0; j < element.options.length; j++) {
				if (element.options[j].selected !=element.options[j].defaultSelected) {
					return true;
				}
			}
		}
	}
	return false;
}
window.onbeforeunload = function(e) {
	e = e || window.event;
	if (formIsDirty(document.forms["someForm"])) {
		// IE 和 Firefox
		if (e) {
			e.returnValue = ”You have unsaved changes.”;
		}
		// Safari browser
		return ”You have unsaved changes.”;
	}
};

7. Disable back button

<SCRIPT type=”text/javascript”>
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload=”noBack();”
onpageshow=”if (event.persisted) noBack();” onunload=”">

8. Check and uncheck listbox

For a list of check boxes, we can pass true or false to check and uncheck all the check boxes.

function listboxSelectDeselect(listID, isSelect) {
	var listbox = document.getElementById(listID);
	for(var count=0; count < listbox.options.length; count++) {
		listbox.options[count].selected = isSelect;
	}
}

9. Initialize array quickly

Below is one method to quickly initialize one array

var numbers = [];
for(var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100]

10. Get the fixed digit decimal number

Need to use toFixed method:

var num = 2.443242342;
alert(num.toFixed(2)); // 2.44
While use toPrecision(x) to provide fixed precision, here x is the number of all digits in the number:
num = 500.2349;
result = num.toPrecision(4);//Output : 500.2

11. Remove duplicated elements in an array

function removeDuplicates(arr) {
	var temp = {};
	for (var i = 0; i < arr.length; i++)
		temp[arr[i]] = true;
	var r = [];
	for (var k in temp)
		r.push(k);
	return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//Output: uniquefruits ['apple', 'orange', 'peach', 'strawberry'];

12. Encode URL

var myOtherUrl =“http://example.com/index.html?url=” + encodeURIComponent(myUrl);

Source : 码农网 » 12个提高效率的JavaScript实用技巧

JAVASCRIPT  TIPS  ARRAY 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  1 COMMENT


AnonnimuZZ [Reply]@ 2020-08-09 07:14:08
Yeahhh Cool. Thank For Help!