


Detailed explanation of JavaScript arrays and loops_javascript skills
May 16, 2016 pm 04:02 PMAn array is an ordered combination of elements. In JavaScript, arrays can be created using formal object notation, or they can be initialized using literal notation.
var arrObject = new Array("val1", "val2"); // Array as object
var arrLiteral = ["val1", "val2"]; // Array literal
For developers, there is no difference: an Array method can be called on both literals and objects. For the JavaScript engine, an array literal must be reinterpreted every time it is accessed, especially when used within a function.
Use the new operator to create a new Array object:
var arrObject = new Array();
You can also create a new array with certain values:
var arrObject = new Array("val1", "val2");
Arrays in JavaScript are indexed from 0, which means that the index of the first element is 0 and the last element is the length of the array minus 1.
1. Loop through the array
Problem: Want to easily access all elements of an array.
Solution:
To access an array, the most common way is to use a for loop:
<script type="text/javascript">
var animals = new Array("cat", "dog", "whale", "seal");
var animalString = "";
for (var i = 0; i < animals.length - 1; i ) {
animalString = animals[i] " ";
}
alert(animalString);
</script>
Discussion:
The for loop can be used to access each element of the array. The array starts at 0, and the array property length is used to set the end of the loop.
2. Store and access values in order
Problem: Want to store values in such a way that they can be accessed sequentially the way they are stored;
Solution:
To store and access values in the order they are received, create a first-in, first-out (FIFO) queue. Use the push method of the JavaScript Array object to add items to the queue, and use shift to get the items:
<script type="text/javascript">
//Create a new array
var queue = new Array();
// Push 3 items
Queue.push("first");
Queue.push("second");
Queue.push("third");
// Get two entries
alert(queue.shift());
alert(queue.shift());
alert(queue);
</script>
Discussion:
The Array push method creates a new array element and adds it to the end of the array:
queue.push("first");
Each time an element is pushed, the count of array elements is incremented.
The Array shift method extracts an array element from the front of the array, deletes it from the array, and returns the element:
var elem = queue.shift();
For each element of the shift operation, the array element will be decremented, because shift not only returns the item, but also modifies the array.
3. Store and access values in reverse order
Problem: I want to store values in a way that accesses the values in reverse order, accessing the most recently stored value first, which is a last-in-first-out (LIFO) stack.
Solution:
To store values in reverse order, create a LIFO stack. Use the push method of the JavaScript Array object to add items to the stack, and the pop method to get items:
<script type="text/javascript">
//Create a new array
var stack = new Array();
// Push 3 items
stack.push("first");
stack.push("second");
stack.push("third");
// Pop up two items
alert(stack.pop()); // Return the third item
alert(stack.pop()); // Return the second item
alert(stack); // Return the first item
</script>
Discussion:
The stack is also an array, where each newly added element is at the top of the stack and is obtained in last-in-first-out order.
The Array push method creates a new element and adds it to the end of the array:
stack.push("first");
Each time an element is pushed, the array element count is incremented.
The Array pop method extracts an array element from the tail of the array, removes it from the array, and returns the element:
var elem = stack.pop();
Every time an element is popped, the array element count will be decremented, because popping also modifies the array.
4. Search in the array
Question: I want to search for a specific value in an array and, if found, get the index of the array element.
Solution:
Use the new (ECMAScript 5) Array object methods indeOf and lastIndexOf:
<script type="text/javascript">
var animals = new Array("dog", "cat", "seal", "elephant", "lion");
alert(animals.indexOf("elephant")); // print out 3
alert(animals.indexOf("seal", 2)); // print out 2
</script>
Although browsers sometimes support both indexOf and lastIndexOf, this is only formalized in the ECMAScript 5 version. Both methods accept a search value, which is then compared to each element in the array. If the value is found, both methods return an index into the array element. If no value is found, -1 is returned. indexOf returns the first element found and lastIndexOf returns the last element found.
See:
Not all browsers support indexOf and lastindexOf. The solution for this function:
<script type="text/javascript">
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt/*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from = len;
}
for (; from < len; from ) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
}
}
</script>
5、对每个数字元素应用一个函数
问题:想要使用一个函数来检查一个数组值,如果满足给定的条件,就替换它。
解决方案:
使用新的ECMAScript 5 Array对象的forEach方法,来针对每个数组元素都绑定一个回调函数:
<script type="text/javascript">
function replaceElement(element, index, array) {
if (element == "ab") {
array[index] = "**";
}
}
var charSets = new Array("ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab");
//对每个数组元素应用函数
charSets.forEach(replaceElement)
alert(charSets); // 打印出**,bb,cd,**,cc,**,dd,**
</script>
讨论:
forEach方法接受一个参数,这个参数是个函数。该函数自身有3个参数:数组元素,元素的索引和数组。
参见:
大多数浏览器都支持forEach。然而,对于那些不支持的浏览器,可以使用Array.prototype属性来模拟forEach行为。
<script type="text/javascript">
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fun/*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i = 0; i < len; i ) {
if (i in this) {
fun.call(thisp, this[i], i, this);
}
}
};
}
</script>
6. Create a filtered array
Question: I want to filter the values of elements in an array and assign the results to a new array.
Solution:
Use the filter method of the Array object:
<script type="text/javascript">
Function removeChars(element, index, array) {
return element !== "**";
}
var charSets = new Array("**", "bb", "cd", "**", "cc", "**", "dd", "**");
var newArray = charSets.filter(removeChars);
alert(newArray); // bb,cd,cc,dd
</script>
Discussion:
The filter method is a newly added method in ECMAScript 5, which applies a callback function to each array element. The function passed as a parameter to the filter method returns a boolean value, true or false, based on the result of testing the array element. This return value determines whether the array element is added to a new array. If the function returns true, it will be added; otherwise, it will not be added.
See:
For simulation implementation of browsers that do not support the filter method:
<script type="text/javascript">
If (!Array.prototype.filter) {
Array.prototype.filter = function (fun/*, thisp*/) {
var len = this.length >>> 0;
If (typeof fun != "function") {
throw new TypeError();
}
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i ) {
If (i in this) {
var val = this[i]; // Placing fun modifies this
If (fun.call(thisp, val, i, this)) {
res.push(val);
}
}
}
return res;
};
}
</script>
7. Verify array content
Problem: Want to ensure that an array meets a certain condition.
Solution:
Use the every method of the Array object to check each element of the given condition.
<script type="text/javascript">
Function testValue(element, index, array) {
var re = /^[a-zA-Z] $/;
return re.test(element);
}
var elemSet = new Array("**", 123, "abc", "-", "AAA");
alert(elemSet.every(testValue));
</script>
Discussion:
The every and some methods of the Array object are both the latest ECMAScript 5 Array methods. The difference is that when using the every method, as long as the function returns a false value, the processing will end and the method returns false. The some method will continue to test each array element until the callback function returns true. At this time, other elements are no longer verified, and this method returns true. If the callback function tests all elements and does not return true at any time, some method returns false.
See:
Implementation method for browsers that do not support every and some:
<script type="text/javascript">
If (!Array.prototype.some) {
Array.prototype.some = function (fun/*, thisp*/) {
var i = 0,
len = this.length >>> 0;
If (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (; i < len; i ) {
If (i in this
&& fun.call(thisp, val, i, this)) {
Return true
}
}
return false;
};
}
if (!Array.prototype.every) {
Array.prototype.every = function (fun/*, thisp*/) {
var len = this.length >>> 0;
If (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i=0; i < len; i ) {
If (i in this
&& fun.call(thisp, val, i, this)) {
Return false
}
}
return true;
};
}
</script>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to remove duplicate elements from PHP array using foreach loop?

PHP array key value flipping: Comparative performance analysis of different methods

PHP array multi-dimensional sorting practice: from simple to complex scenarios

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods

Application of PHP array grouping function in data sorting

What are the alternatives to recursive calls in Java functions?

The role of PHP array grouping function in finding duplicate elements
