Home > Web Front-end > JS Tutorial > body text

Explanation of tips for Array arrays in JavaScript

不言
Release: 2018-07-13 10:01:30
Original
1518 people have browsed it

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

1. Array.prototype.push ()

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
Copy after login

Although obj is not an array, the push method successfully increases the length property of obj, just like we would with an actual array.

2. Array.prototype.sort()

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.

If

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:

  • If

    compareFunction(a, b) is less than 0, then a will be arranged before b;

  • If

    compareFunction(a, b) is equal to 0, the relative position of a and b remains unchanged;

  • If

    compareFunction(a, b) is greater than 0, b will be arranged before a.

The comparison function format is as follows (both strings and arrays can be compared):

function compare(a, b) {
    if (a < b ) {           // 按某种排序标准进行比较, a 小于 b
        return -1;
    }
    if (a > b ) {
        return 1;
    }
    // a must be equal to b
    return 0;
}
Copy after login
3. Array.prototype.unshift()

var arr = [1, 2];
arr.unshift(-2, -1);    // = 5
// arr is [-2, -1, 1, 2]
Copy after login

4 . Array.prototype.concat()

Returns a new array (

shallow copy) and will not affect the original array.

  • If the parameter is an array, put the elements of the array into the result;

  • If the parameter is not an array, put the parameter itself Results are in progress.

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]
Copy after login
5. Array.prototype.forEach()

array.forEach(callback(currentValue, index, array){
    //do something
}, thisArg)

array.forEach(callback[, thisArg])
Copy after login

Among them:

thisArg is an optional parameter, used when executing the callback function The value of this (reference object).

The following functions also have the optional parameter

thisArg, and its usage is consistent with Array.prototype.forEach():

  • Array.prototype.forEach()

  • Array.prototype.every()

  • ##Array.prototype.some()
  • Array.prototype.filter()
  • Array.prototype.map()
  • Array.prototype.reduce ()
  • Array.prototype.reduceRight()
  • 6. Array.prototype.map()

Usage tips Case

// 下面的语句返回什么呢:
["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]
Copy after login

7.Array.prototype.reduce()

arr.reduce(callback[, initialValue])
##Array. prototype.reduceRight()
is similar to its usage, traversing from right to left.

Parameters:

    callback
  • : Function that executes each value in the array, contains four parameters:

    • accumulator
    • : The accumulator accumulates the return value of the callback; it is the accumulated value returned the last time the callback was called, or

      initialValue (as shown below).

    • currentValue
    • : The element being processed in the array.

    • currentIndex
    • : Optional, the index of the current element being processed in the array. If initialValue is provided, the index number is 0, otherwise the index is 1.

    • array
    • : Optional, the array to call

      reduce.

    initialValue
  • : Optional, the value used as the first parameter of the first callback call. If no initial value is provided, the first element in the array will be used. Calling

    reduce on an empty array with no initial value will report an error.

    How to run reduce
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
}, 10);

// 20
Copy after login
Example: 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]
Copy after login
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'
// ]
Copy after login
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]
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!