Home >Web Front-end >JS Tutorial >Explanation of tips for Array arrays in JavaScript
This article mainly introduces the tips about Array arrays in JavaScript. It has certain reference value. Now I share it with you. Friends in need can refer to it
Using objects like arrays:
var obj = { length: 0, addElem: function addElem (elem) { // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); } }; // Let's add some empty objects just to illustrate. obj.addElem({}); obj.addElem({}); console.log(obj.length); // → 2
Although obj is not an array, the push method successfully increases the length property of obj, just like we would with an actual array.
arr.sort(compareFunction)
Parameters: compareFunction
Optional. Used to specify functions arranged in a certain order. If omitted, elements are sorted according to the Unicode position of each character of the string converted to.
compareFunction is specified, the array will be sorted according to the return value of calling the function. That is, a and b are two elements to be compared:
compareFunction(a, b) is less than 0, then a will be arranged before b;
compareFunction(a, b) is equal to 0, the relative position of a and b remains unchanged;
compareFunction(a, b) is greater than 0, b will be arranged before a.
function compare(a, b) { if (a < b ) { // 按某种排序标准进行比较, a 小于 b return -1; } if (a > b ) { return 1; } // a must be equal to b return 0; }3. Array.prototype.unshift()
var arr = [1, 2]; arr.unshift(-2, -1); // = 5 // arr is [-2, -1, 1, 2]
shallow copy) and will not affect the original array.
var num1 = [1, 2, 3], num2 = [4, 5, 6], num3 = [7, 8, 9]; var nums = num1.concat(num2, num3); console.log(nums); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9]; var alpha = ['a', 'b', 'c']; var alphaNumeric = alpha.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3]5. Array.prototype.forEach()
array.forEach(callback(currentValue, index, array){ //do something }, thisArg) array.forEach(callback[, thisArg])
thisArg is an optional parameter, used when executing the callback function The value of
this (reference object).
thisArg, and its usage is consistent with
Array.prototype.forEach():
// 下面的语句返回什么呢: ["1", "2", "3"].map(parseInt); // 你可能觉的会是[1, 2, 3] // 但实际的结果是 [1, NaN, NaN] // 通常使用parseInt时,只需要传递一个参数. // 但实际上,parseInt可以有两个参数.第二个参数是进制数. // 可以通过语句"alert(parseInt.length)===2"来验证. // map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素, // 元素索引, 原数组本身. // 第三个参数parseInt会忽视, 但第二个参数不会,也就是说, // parseInt把传过来的索引值当成进制数来使用.从而返回了NaN. function returnInt(element) { return parseInt(element, 10); } ['1', '2', '3'].map(returnInt); // [1, 2, 3] // 意料之中的结果 // 也可以使用简单的箭头函数,结果同上 ['1', '2', '3'].map( str => parseInt(str) ); // 一个更简单的方式: ['1', '2', '3'].map(Number); // [1, 2, 3] // 与`parseInt` 不同,下面的结果会返回浮点数或指数: ['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
7.Array.prototype.reduce()
arr.reduce(callback[, initialValue])
##Array. prototype.reduceRight()
is similar to its usage, traversing from right to left. Parameters:
initialValue (as shown below).
reduce.
reduce on an empty array with no initial value will report an error.
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){ return accumulator + currentValue; }, 10); // 20Example: Convert a two-dimensional array to one dimension
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); }, [] ); // flattened is [0, 1, 2, 3, 4, 5]Example: Use the spread operator and initialValue binding to contain Array in object array
// friends - an array of objects // where object field "books" - list of favorite books var friends = [{ name: 'Anna', books: ['Bible', 'Harry Potter'], age: 21 }, { name: 'Bob', books: ['War and peace', 'Romeo and Juliet'], age: 26 }, { name: 'Alice', books: ['The Lord of the Rings', 'The Shining'], age: 18 }]; // allbooks - list which will contain all friends' books + // additional list contained in initialValue var allbooks = friends.reduce(function(prev, curr) { return [...prev, ...curr.books]; }, ['Alphabet']); // allbooks = [ // 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', // 'Romeo and Juliet', 'The Lord of the Rings', // 'The Shining' // ]Example: Array deduplication
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; let result = arr.sort().reduce((init, current)=>{ if(init.length===0 || init[init.length-1]!==current){ init.push(current); } return init; }, []); console.log(result); //[1,2,3,4,5]The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website ! Related recommendations:
How to use the Angular-UI Bootstrap component to implement alerts
The above is the detailed content of Explanation of tips for Array arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!