search
HomeWeb Front-endJS TutorialJavaScript native array functions explained

JavaScript native array functions explained

Aug 09, 2017 pm 01:53 PM
javascriptjsexplain

In JavaScript, you can create an array using the JavaScript native array functions explained constructor, or using the array direct variable [], the latter is the preferred method. The JavaScript native array functions explained object inherits from Object.prototype, and executing the typeof operator on the array returns object instead of array. However, [] instanceof JavaScript native array functions explained also returns true. In other words, the implementation of array-like objects is more complicated, such as strings objects, arguments objects, arguments objects are not instances of JavaScript native array functions explained, But it has the length attribute and can get the value through the index, so it can be looped like an array.

In this article, I will review some of the array prototype methods and explore their uses.

  • Loop: .forEach

  • Judgment: .some and .every

  • Distinguish between .join and .concat

  • Implementation of stack and queue : .pop, .push, .shift, and .unshift

  • models Mapping: .map

  • Query: .filter

  • Sort: . sort

  • Calculation: .reduce and .reduceRight

  • Copy:.slice

  • Powerful.splice

  • Find: .indexOf

  • Operator: in

  • come closer.reverse

JavaScript native array functions explained

Loop:.forEach

This is the simplest method in JavaScript, but IE7 and IE8 do not support this method.
.forEach has a callback function as a parameter. When traversing the array, it will be called for each array element. The callback function accepts three parameters:

  • value: The current element

  • index: The index of the current element

  • array : JavaScript native array functions explained to be traversed
    Additionally, an optional second parameter can be passed as the context for each function call (this).

['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {    this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])out.join(&#39;&#39;)// <- &#39;awesome&#39;123456

.join will be mentioned later. In this example, it is used to splice different elements in the array. The effect is similar to out[0] + '' + out[1] + '' + out[2] + '' + out[n].
Cannot interrupt the .forEach loop, and throwing an exception is not a wise choice. Fortunately we have another way to interrupt operations.

Judgment: .some and .every

If you have used enumerations in .NET, these two methods are the same as .Any(x => x.IsAwesome), .All(x => x.IsAwesome) are similar. The parameters of
and .forEach are similar and require a callback function containing three parameters: value, index, and array. And there is also an optional second context parameter. MDN describes .some as follows:

some will execute the callback function for each element in the array until the callback function returns true. If the target element is found, some returns true immediately, otherwise some returns false. The callback function is only executed for array indexes with assigned values; it is not called for deleted or unassigned elements.

max = -Infinity
satisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {    if (value > max) max = value    return value < 10})

console.log(max)// <- 12satisfied// <- true1234567891011

Note that when the value of the callback function , the function loop is interrupted. The operating principle of <code>.every is similar to .some, but the callback function returns false instead of true.

Distinguish between .join and .concat

##.join and .concat are often confused. .join(separator) Use separator as the separator to splice array elements and return the string form. If separator is not provided, the default will be used. ,. .concat will create a new array as a shallow copy of the source array.

  • .concatCommon usage: array.concat(val, val2, val3, valn)

  • .concatReturns a new array

  • array.concat()Without parameters, returns the shallow representation of the source array copy. Shallow copy means that the new array and the original array maintain the same object reference, which is usually a good thing. For example:

var a = { foo: &#39;bar&#39; }
var b = [1, 2, 3, a]
var c = b.concat()

console.log(b === c)// <- falseb[3] === a && c[3] === a// <- true123456789

栈和队列的实现:.pop, .push, .shift.unshift

每个人都知道.push可以再数组末尾添加元素,但是你知道可以使用[].push('a', 'b', 'c', 'd', 'z')一次性添加多个元素吗?
.pop 方法是.push 的反操作,它返回被删除的数组末尾元素。如果数组为空,将返回void 0 (undefined),使用.pop.push可以创建LIFO (last in first out)栈。

function Stack () {    this._stack = []
}

Stack.prototype.next = function () {    return this._stack.pop()
}

Stack.prototype.add = function () {    return this._stack.push.apply(this._stack, arguments)
}

stack = new Stack()
stack.add(1,2,3)

stack.next()// <- 31234567891011121314151617

相反,可以使用.shift.unshift创建FIFO (first in first out)队列。

function Queue () {
    this._queue = []
}

Queue.prototype.next = function () {    return this._queue.shift()
}

Queue.prototype.add = function () {    return this._queue.unshift.apply(this._queue, arguments)
}

queue = new Queue()
queue.add(1,2,3)

queue.next()// <- 1Using .shift (or .pop) is an easy way to loop through a set of array elements, while draining the array in the process.

list = [1,2,3,4,5,6,7,8,9,10]while (item = list.shift()) {
    console.log(item)
}

list// <- []123456789101112131415161718192021222324252627

模型映射:.map

.map为数组中的每个元素提供了一个回调方法,并返回有调用结果构成的新数组。回调函数只对已经指定值的数组索引执行;它不会对已删除的或未指定值的元素调用。

JavaScript native array functions explained.prototype.map 和上面提到的.forEach.some.every有相同的参数格式:.map(fn(value, index, array), thisArgument)

values = [void 0, null, false, &#39;&#39;]
values[7] = void 0result = values.map(function(value, index, array){    console.log(value)    return value
})// <- [undefined, null, false, &#39;&#39;, undefined × 3, undefined]12345678

undefined × 3很好地解释了.map不会对已删除的或未指定值的元素调用,但仍然会被包含在结果数组中。.map在创建或改变数组时非常有用,看下面的示例:

// casting[1, &#39;2&#39;, &#39;30&#39;, &#39;9&#39;].map(function (value) {    return parseInt(value, 10)
})// 1, 2, 30, 9[97, 119, 101, 115, 111, 109, 101].map(String.fromCharCode).join(&#39;&#39;)// <- &#39;awesome&#39;// a commonly used pattern is mapping to new objectsitems.map(function (item) {    return {
        id: item.id,
        name: computeName(item)
    }
})12345678910111213141516

查询:.filter

filter对每个数组元素执行一次回调函数,并返回一个由回调函数返回true的元素组成的新数组。回调函数只会对已经指定值的数组项调用。

通常用法:.filter(fn(value, index, array), thisArgument),跟C#中的LINQ表达式和SQL中的where语句类似,.filter只返回在回调函数中返回true值的元素。

[void 0, null, false, &#39;&#39;, 1].filter(function (value) {    return value
})// <- [1][void 0, null, false, &#39;&#39;, 1].filter(function (value) {    return !value
})// <- [void 0, null, false, &#39;&#39;]123456789

排序:.sort(compareFunction)

如果没有提供compareFunction,元素会被转换成字符串并按照字典排序。例如,”80”排在”9”之前,而不是在其后。

跟大多数排序函数类似,JavaScript native array functions explained.prototype.sort(fn(a,b))需要一个包含两个测试参数的回调函数,其返回值如下:

  • a在b之前则返回值小于0

  • a和b相等则返回值是0

  • a在b之后则返回值小于0

[9,80,3,10,5,6].sort()// <- [10, 3, 5, 6, 80, 9][9,80,3,10,5,6].sort(function (a, b) {    return a - b
})// <- [3, 5, 6, 9, 10, 80]1234567

计算:.reduce.reduceRight

这两个函数比较难理解,.reduce会从左往右遍历数组,而.reduceRight则从右往左遍历数组,二者典型用法:.reduce(callback(previousValue,currentValue, index, array), initialValue)
previousValue 是最后一次调用回调函数的返回值,initialValue则是其初始值,currentValue是当前元素值,index是当前元素索引,array是调用.reduce的数组。
一个典型的用例,使用.reduce的求和函数。

JavaScript native array functions explained.prototype.sum = function () {    return this.reduce(function (partial, value) {        return partial + value
    }, 0)
};

[3,4,5,6,10].sum()// <- 2812345678

如果想把数组拼接成一个字符串,可以用.join实现。然而,若数组值是对象,.join就不会按照我们的期望返回值了,除非对象有合理的valueOftoString方法,在这种情况下,可以用.reduce实现:

function concat (input) {    return input.reduce(function (partial, value) {        if (partial) {            partial += &#39;, &#39;
        }        return partial + value
    }, &#39;&#39;)
}

concat([
    { name: &#39;George&#39; },
    { name: &#39;Sam&#39; },
    { name: &#39;Pear&#39; }
])// <- &#39;George, Sam, Pear&#39;123456789101112131415

复制:.slice

.concat类似,调用没有参数的.slice()方法会返回源数组的一个浅拷贝。.slice有两个参数:一个是开始位置和一个结束位置。
JavaScript native array functions explained.prototype.slice 能被用来将类数组对象转换为真正的数组。

JavaScript native array functions explained.prototype.slice.call({ 0: &#39;a&#39;, 1: &#39;b&#39;, length: 2 })
// <- [&#39;a&#39;, &#39;b&#39;]12

这对.concat不适用,因为它会用数组包裹类数组对象。

JavaScript native array functions explained.prototype.concat.call({ 0: &#39;a&#39;, 1: &#39;b&#39;, length: 2 })
// <- [{ 0: &#39;a&#39;, 1: &#39;b&#39;, length: 2 }]12

此外,.slice的另一个通常用法是从一个参数列表中删除一些元素,这可以将类数组对象转换为真正的数组。

function format (text, bold) {    if (bold) {        text = &#39;<b>&#39; + text + &#39;</b>&#39;
    }
    var values = JavaScript native array functions explained.prototype.slice.call(arguments, 2)

    values.forEach(function (value) {        text = text.replace(&#39;%s&#39;, value)
    })    return text}format(&#39;some%sthing%s %s&#39;, true, &#39;some&#39;, &#39;other&#39;, &#39;things&#39;)// <- <b>somesomethingother things</b>123456789101112131415

强大的.splice

.splice 是我最喜欢的原生数组函数,只需要调用一次,就允许你删除元素、插入新的元素,并能同时进行删除、插入操作。需要注意的是,不同于`.concat.slice,这个函数会改变源数组。

var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]
var spliced = source.splice(3, 4, 4, 5, 6, 7)

console.log(source)// <- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13]spliced// <- [8, 8, 8, 8]12345678

正如你看到的,.splice会返回删除的元素。如果你想遍历已经删除的数组时,这会非常方便。

var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]var spliced = source.splice(9)

spliced.forEach(function (value) {
    console.log(&#39;removed&#39;, value)
})// <- removed 10// <- removed 11// <- removed 12// <- removed 13console.log(source)// <- [1, 2, 3, 8, 8, 8, 8, 8, 9]12345678910111213

查找:.indexOf

利用.indexOf 可以在数组中查找一个元素的位置,没有匹配元素则返回-1。我经常使用.indexOf的情况是当我有比较时,例如:a === 'a' || a === 'b' || a === 'c',或者只有两个比较,此时,可以使用.indexOf['a', 'b', 'c'].indexOf(a) !== -1
注意,如果提供的引用相同,.indexOf也能查找对象。第二个可选参数用于指定开始查找的位置。

var a = { foo: &#39;bar&#39; }
var b = [a, 2]

console.log(b.indexOf(1))// <- -1console.log(b.indexOf({ foo: &#39;bar&#39; }))// <- -1console.log(b.indexOf(a))// <- 0console.log(b.indexOf(a, 1))// <- -1b.indexOf(2, 1)// <- 11234567891011121314151617

如果你想从后向前搜索,可以使用.lastIndexOf

操作符:in

在面试中新手容易犯的错误是混淆.indexOfin操作符:

var a = [1, 2, 5]1 in a// <- true, but because of the 2!5 in a// <- false1234567

问题是in操作符是检索对象的键而非值。当然,这在性能上比.indexOf快得多。

var a = [3, 7, 6]1 in a === !!a[1]// <- true1234

走近.reverse

该方法将数组中的元素倒置。

var a = [1, 1, 7, 8]a.reverse()// [8, 7, 1, 1]1234

.reverse 会修改数组本身。

译文出处:http://www.ido321.com/1568.html

本文根据@Nicolas Bevacqua的《Fun with JavaScript Native JavaScript native array functions explained Functions》所译,整个译文带有我自己的理解与思想,如果译得不好或有不对之处还请同行朋友指点。如需转载此译文,需注明英文出处:http://modernweb.com/2013/11/25/fun-with-javascript-native-array-functions/。

The above is the detailed content of JavaScript native array functions explained. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools