1.1 Definition of array in Javascript
The standard definition of array: a linear collection of stored elements. The elements can be accessed arbitrarily through the index. The index is usually a number and is used to calculate the offset of the storage location between elements.
However, an array in JavaScript is a special object. The index used to represent the offset is a property of the object, and the index may be an integer. However, these numeric indices are converted to string types internally because property names in JavaScript objects must be strings.
2.2 Use arrays
2.2.1 Create arrays
var nums = [1,2,3,4]; || This method is more efficient
var nums = new Array(1,2,3,4) ;
2.2.2 Read and write arrays
In an assignment statement, use the [] operator to assign data to an array. For example, the following loop assigns numbers from 1 to 100 to an array:
var nums = [];for (var i =0; i<100;i++){ nums[i] = i+1;}
can also be used The [ ] operator reads elements in the array:
var nums = [1,2,3,4]; var sum = nums[0]+nums[1]+nums[2]+nums[3]; console.log(sum)
2.2.3 Generating an array from a string
var sentence = "the quick brown fox jumped over the lazy dog"; var words = sentence.split(" "); for (var i=0; i<words.length;i++){ console.log("word " + i + ":" +words[i]); }
In the above program, the splite() method is called, and a sentence is divided into and parts and save each part as an element in a newly created array.
2.2.4 Operations on array integrity
1. Assign one array to another array
var nums = []; for (var i = 0; i<10;i++){ nums[i] = i+1; } var samenums = nums;
But the above assignment operation only adds a new reference to the assigned array. When the value of an array is modified through the original reference, the other reference will also be changed.
var nums = []; for (var i = 0; i<10;i++){ nums[i] = i+1; } var samenums = nums; nums[0] = 400; console.log(samenums[0]); //显示400
This behavior is a shallow copy, and the new array still points to the original array.
A better solution is to deep copy, copying each element in the original array to the new array.
//写个深复制函数function copy(arr1,arr2){ for (var i = 0;i<arr1.length;i++){ arr2[i] = arr1[i]; }}var nums = [];for (var i = 0; i<10;i++){ nums[i] = i+1;}var samenums = [];copy(nums,samenums);nums[0] = 400;console.log(samenums[0]); //显示1
2.3 Access function
2.3.1 Find element =====indexOf()
is used to find whether the parameter passed in exists in the target array. If the target array contains this parameter, the index of the element in the array is returned; if not, -1 is returned.
2.3.2 String representation of array ===== join() and toString()
Both methods return a string containing all elements of the array, separated by commas.
2.3.3 Create a new array from an existing array =====concat() and splice()
concat() methods can merge multiple arrays to create a new array. The
splice() method intercepts a subset of an array to create a new array. The first parameter of this method is the starting index of interception, and the second parameter is the length of interception.
var itDiv = ["Mike","Clayton","Terrill","Raymond","Cynthia","Danny","Jennifer"]; var dmpDept = itDiv.splice(3,3); // Raymond,Cynthia,Danny print(cisDept); var cisDept = itDiv; console.log(dmpDept);// Mike,Clayton,Terrill,Jennifer
2.4 Variable function
2.4.1 Adding elements to the array======push() and unshift()
push() methods add an element to the end of the array.
The unshift() method can add elements to the beginning of the array.
var nums = [2,3,4,5]; console.log(nums); // 2,3,4,5 var newnum = 1; nums.unshift(newnum); console.log(nums); // 1,2,3,4,5 nums = [3,4,5]; nums.unshift(newnum,1,2); console.log(nums); // 1,2,3,4,5
2.4.2 Delete elements from the array pop() and shift()
pop() methods can delete elements at the end of the array.
var nums = [1,2,3,4,5,9]; nums.pop(); console.log(nums); // 1,2,3,4,5
shift() method can delete the first element of the array.
var nums = [9,1,2,3,4,5]; nums.shift(); console.log(nums); // 1,2,3,4,5
pop() 和 shift() 方法都将删掉的元素作为方法的 返回值返回,因此可以使用一个变量来保存删除的元素:
var nums = [6,1,2,3,4,5]; var first = nums.shift(); // first gets the value 9 nums.push(first); console.log(nums); // 1,2,3,4,5,6
2.4.3 从数组中间位置添加和删除元素=====splice()
用splice()方法为数组添加元素,需提供如下参数:
起始索引(就是希望开始添加元素的地方)
需要删除的元素个数(添加元素时该参数设为0)
想要添加进数组的元素
such as:
var nums=[1,2,3,7,8,9]; var newElements = [4,5,6]; nums.splice(3,0,newElements); console.log(nums); //1,2,3,4,5,6,7,8,9
下面是用splice()删除数组元素的例子:
var nums = [1,2,3,100,200,4,5]; nums.splice(3,2); console.log(nums); //1,2,3,4,5
2.4.4 为数组排序
1.reverse() ====> 将数组中元素的顺序进行翻转
2.sort() ======>对字符型的元素按字典顺序进行排序
对于数字类型的元素,如果要用sort()排序,可以在调用方法时传入一个大小比较函数,排序时,sort()方法会根据该函数比较数组中两个元素的大小,来决定整个数组的顺序。
function compare(num1,num2){ return num1-num2; } var nums = [3,4,1,80,27]; nums.sort(compare);
sort()使用了compare()函数对数组按照数字大小进行排序,而不是按照字典顺序。
2.5 迭代器方法
2.5.1 不生成新数组的迭代器方法
1.forEach()
接受一个函数作为参数,并对数组中的每个元素使用该函数。
function square(num){ console.log(num,num*num); } var nums = [1,2,3,4,5,6]; nums.forEach(square);
2.every()
接受一个返回值为布尔型的函数,对数组中的每个元素使用该函数。如果对于所有的元素,该函数都返回true,则该方法返回true。
function isEven(num){ return num%2 == 0; } var nums = [2,4,6,8]; var even = nums.every(isEven); if(even){ console.log("all numbers are even"); }else{ console.log("not all numbers are even"); }
可以改改数组里的元素试试。
3.some()
some() 方法也接受一个返回值为布尔类型的函数,只要有一个元素使得该函数返回 true, 该方法就返回 true.
function isEven(num) { return num % 2 == 0; } var nums = [1,2,3,4,5,6,7,8,9,10]; var someEven = nums.some(isEven); if (someEven) { console.log("some numbers are even"); } else { console.log("no numbers are even"); } nums = [1,3,5,7,9]; someEven = nums.some(isEven); if (someEven) { console.log("some numbers are even"); } else { console.log("no numbers are even");}
4.reduce()
接受一个函数,返回一个值。该方法会从一个累加值开始,不断对累加值和 数组中的后续元素调用该函数,直到数组中的最后一个元素,最后返回得到的累加值。
下 面这个例子展示了如何使用 reduce() 方法为数组中的元素求和:
function add(runningTotal,currentValue){ return runningTotal + currentValue; } var nums = [1,2,3,4,5,6]; var sum = nums.reduce(add); console.log(sum);
reduce() 方法和 add() 函数一起,从左到右,依次对数组中的元素求和。
reduce() 方法也可以用来将数组中的元素连接成一个长的字符串:
function concat(accumulatedString,tiem){ return accumulatedString + item; } var words = ["the ", "quick ","brown ", "fox "]; var sentence = words.reduce(concat); console.log(sentence);
2.5.2 生成新数组的迭代器方法
1. map()
map() 和 forEach() 有点儿像,对 数组中的每个元素使用某个函数。两者的区别是 map() 返回一个新的数组,该数组的元素 是对原有元素应用某个函数得到的结果。
function curve(grade){ return grade += 5; } var grades = [78,89,92,74]; var newgrades = grades.map(curve); console.log(newgrades); // 83,94,97,79
2. filter()
filter() 和 every() 类似,传入一个返回值为布尔类型的函数。和 every() 方法不同的是, 当对数组中的所有元素应用该函数,结果均为 true 时,该方法并不返回 true,而是返回 一个新数组,该数组包含应用该函数后结果为 true 的元素。
function passing(num) { return num >= 60; } var grades = []; for (var i = 0; i < 20; ++i) { grades[i] = Math.floor(Math.random() * 101); } var passGrades = grades.filter(passing); console.log("All grades: "); console.log(grades); console.log("Passing grades: "); console.log(passGrades);