查看“︁JavaScript/array”︁的源代码
来自康健生活
←
JavaScript/array
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 引言 == === 特点 === * 相同的数据类型 * 连续的线性内存 === 稀疏数组 === 有空值的数组。 == 方法 == {| class="wikitable" |- | [[/find|find]] || [[/forEach|forEach]] || [[/map|map]] || [[/reduce|reduce]] |- | [[/every|every]] || [[/some|some]] || [[/filter|filter]] |- | [[/indexOf|indexOf]] || [[/reverse|reverse]] || [[/解构|解构...]] |} == holes == 数组空洞(缺失索引)<ref>[https://exploringjs.com/es6/ch_arrays.html#sec_array-holes New Array features-ES6 and holes in Arrays][OL], https://exploringjs.com/es6/ch_arrays.html#sec_array-holes.</ref>。 === 示例 === {{leftrightflex|<syntaxhighlight lang="javascript"> Object.keys(['a',, 'c']);</syntaxhighlight>|{{consoleout|<pre> ['0', '2'] </pre>}}}} == 创建数组 == === new === {{leftrightflex|<syntaxhighlight lang="javascript"> new Array(3); // or [...new Array(3)].map((_, i) => i);</syntaxhighlight>|{{consoleout|<pre> [空属性 × 3] [0, 1, 2] </pre>}}}} === copyWithin === {{leftrightflex|<syntaxhighlight lang="javascript"> [...new Array(5)].map((_, i) => i).copyWithin(3); // or [...new Array(5)].map((_, i) => i).copyWithin(2, 3, 4);</syntaxhighlight>|{{consoleout|<pre> [0, 1, 2, 0, 1] [0, 1, 3, 3, 4] </pre>}}}} === apply === {{leftrightflex|<syntaxhighlight lang="javascript"> Array.apply(null, Array(3)); // or Array.apply(null, [, , ,]); // or Array.apply(null, Array(3)).map((_, i) => i);</syntaxhighlight>|{{consoleout|<pre> [undefined, undefined, undefined] [undefined, undefined, undefined] [0, 1, 2] </pre>}}}} === of === {{leftrightflex|<syntaxhighlight lang="javascript"> Array.of(1, 2, 3);</syntaxhighlight>|{{consoleout|<pre> [1, 2, 3] </pre>}}}} === ArrayBuffer === {{leftrightflex|<syntaxhighlight lang="javascript"> new ArrayBuffer(8);</syntaxhighlight>|{{consoleout|<pre> ArrayBuffer(8) byteLength: 8 [[Prototype]]: ArrayBuffer [[Int8Array]]: Int8Array(8) [[Uint8Array]]: Uint8Array(8) [[Int16Array]]: Int16Array(4) [[Int32Array]]: Int32Array(2) [[ArrayBufferByteLength]]: 8 [[ArrayBufferData]]: 258 </pre>}}}} === Array.from === {{leftrightflex|<syntaxhighlight lang="javascript"> Array.from( {length: 3}, (_v, k) => k ); // or Array.from(new Array(3).keys());</syntaxhighlight>|{{consoleout|<pre> [0, 1, 2] [0, 1, 2] </pre>}}}} === fill === {{leftrightflex|<syntaxhighlight lang="javascript"> new Array(3).fill('kangkk');</syntaxhighlight>|{{consoleout|<pre> ['kangkk', 'kangkk', 'kangkk'] </pre>}}}} == 插入 == == 合并 == 合并两个数组。 {{leftrightflex|<syntaxhighlight lang="javascript"> const source = [1, 2]; const target = [3, 4]; const lastItem = source.push.apply(source, target || []); console.log(lastItem); console.log(source);</syntaxhighlight>|{{consoleout|<pre>4 [1, 2, 3, 4] </pre>}}}} == 交换 == === 第三方变量 === <syntaxhighlight lang="javascript"> const temp = array[index1]; array[index1] = array[index2]; array[index2] = temp;</syntaxhighlight> === splice === <syntaxhighlight lang="javascript"> array.splice(index2,1,...array.splice(index1, 1 , array[index2]));</syntaxhighlight> === 解构赋值 === <syntaxhighlight lang="javascript"> [array[index1],array[index2]] = [array[index2],array[index1]];</syntaxhighlight> == 查找 == === 优化 === ==== 二分法 ==== O(log n) == 删除 == === splice === 删除。 {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = ['a', 'b', 'c', 'd', 'e']; const bar = foo.splice(1, 2); console.log(foo); console.log(bar);</syntaxhighlight>|{{consoleout|<pre> ['a', 'd', 'e'] ['b', 'c'] </pre>}}}} 替换。 {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = ['a', 'b', 'c', 'd', 'e']; const bar = foo.splice(1, 2, 'f'); console.log(foo); console.log(bar);</syntaxhighlight>|{{consoleout|<pre> [ 'a', 'f', 'd', 'e' ] [ 'b', 'c' ] </pre>}}}} 添加。 {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = ['a', 'b', 'c', 'd', 'e']; const bar = foo.splice(1, 0, 'f'); console.log(foo); console.log(bar);</syntaxhighlight>|{{consoleout|<pre> [ 'a', 'f', 'b', 'c', 'd', 'e' ] [] </pre>}}}} === delete === {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = ['a', 'b', 'c', 'd', 'e']; delete foo[2]; console.log(foo);</syntaxhighlight>|{{consoleout|<pre> [ 'a', 'b', <1 empty item>, 'd', 'e' ] </pre>}}}} === concat === {{leftrightflex|<syntaxhighlight lang="javascript"> Array.prototype.del = function (n) { if(n < 0) return this; else return this.slice(0, n).concat(this.slice(n + 1, this.length)); } const foo = new Array('a', 'b', 'c', 'd', 'e'); foo.del(3); console.log(foo);</syntaxhighlight>|{{consoleout|<pre> [ 'a', 'b', 'c', 'd', 'e' ] </pre>}}}} == 读取 == == 遍历 == === 判断 === <syntaxhighlight lang="javascript"> if (!this.length || this.length == 0) return this;</syntaxhighlight> == 排序 == === 字符串排序 === {{leftrightflex|<syntaxhighlight lang="javascript"> [ {name: '康健26'}, {name: '康健'}, {name: '康健1'},{name: '康健19'},{name: '兰倩'},{name: '兰倩3'} ].sort((a, b) => { return a.name.localeCompare(b.name) });</syntaxhighlight>|{{consoleout|<pre> (6) [{…}, {…}, {…}, {…}, {…}, {…}] 0: {name: '康健'} 1: {name: '康健1'} 2: {name: '康健19'} 3: {name: '康健26'} 4: {name: '兰倩'} 5: {name: '兰倩3'} </pre>}}}} == 示例 == === 去重 === <syntaxhighlight lang="javascript"> Array.prototype.uniq = function () { if (!this.length || this.length == 0) return this; var res = [], key, hasNaN = false, temp = {}; for (var i = 0 ; i < this.length; i++) { if (typeof this[i] === 'object') { res.push(this[i]); } else if (this[i] != this[i]) { // 如果当前遍历元素是NaN if (!hasNaN) { res.push(this[i]); hasNaN = true; } } else { key = typeof(this[i]) + this[i]; if (!temp[key]) { res.push(this[i]); temp[key] = true; } } } return res; }</syntaxhighlight> <syntaxhighlight lang="javascript"> Array.prototype.uniq = function () { var res = []; var flag = true; this.forEach(function(x) { if (res.indexOf(x) == -1) { if (x != x) { if (flag) { res.push(x); flag = false; } } else { res.push(x); } } }) return res; }</syntaxhighlight> === 数组相减 === a - b {{leftrightflex|<syntaxhighlight lang="javascript"> function sub(source, target) { if ( !source || !target || Object.prototype.toString.call(source) !== "[object Array]" || Object.prototype.toString.call(target) !== "[object Array]" ) { throw new new TypeError("arguments must be array")(); } for (var i = 0, len = target.length; i < len; i++) { for (var j = 0, jen = source.length; j < jen; j++) { if (source[j] === target[i]) { source.splice(j, 1); j--; } } } return source; } console.log(sub([1, 2, 3, 4], [3, 4]));</syntaxhighlight>|{{consoleout|<pre> [ 1, 2 ] </pre>}}}} {{leftrightflex|<syntaxhighlight lang="javascript"> function sub(source, target) { if (Array.isArray(source) && Array.isArray(target)) { return source.filter((i) => !target.includes(i)); } throw new new TypeError("arguments must be array")(); } console.log(sub([1, 2, 3, 4], [3, 4]));</syntaxhighlight>|{{consoleout|<pre> [ 1, 2 ] </pre>}}}} === 数组取不相同部分 === 数字单一元素。 {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = [6, 4, 7, 12]; const bar = [1, 5, 6, 9, 3, 4]; const difference = (source, target) => { return source.concat(target).filter((v, i, arr) => (arr.indexOf(v) === arr.lastIndexOf(v))); } console.log(difference(foo, bar));</syntaxhighlight>|{{consoleout|<pre>7,12,1,5,9,3 </pre>}}}} 根据不同 key 进行区分。 {{leftrightflex|<syntaxhighlight lang="javascript"> const listOfTags = [ { id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 } ]; const keys = ['label', 'color']; const filtered = listOfTags.filter( ( s => o => ( k => !s.has(k) && s.add(k) ) (keys.map(k => o[k]).join('|')) ) (new Set) ); console.log(JSON.stringify(filtered));</syntaxhighlight>|{{consoleout|<pre>[ {"id":1,"label":"Hello","color":"red","sorting":0}, {"id":2,"label":"World","color":"green","sorting":1}, {"id":3,"label":"Hello","color":"blue","sorting":4}, {"id":4,"label":"Sunshine","color":"yellow","sorting":5} ] </pre>}}}} {{Unknown|https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript}} {{leftrightflex|<syntaxhighlight lang="javascript"> const array = [ { "name": "Joe", "age": 17 }, { "name": "Bob", "age": 17 }, { "name": "Carl", "age": 35 } ]; const key = 'age'; const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()]; console.log(JSON.stringify(arrayUniqueByKey));</syntaxhighlight>|{{consoleout|<pre> [ {"name":"Bob","age":17}, {"name":"Carl","age":35} ] </pre>}}}} {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}]; const bar = [{dept_id: 1, email: 'c@x.y'}, {dept_id: 2, email: 'd@x.y'}, {dept_id: 3, email: 'e@x.y'}]; const values = Object.values( foo.concat(bar).reduce((a, b) => { if (!a[b.email]) a[b.email] = b return a }, {}) ) console.log(JSON.stringify(values));</syntaxhighlight>|{{consoleout|<pre> [ {"id":1,"email":"a@x.y"}, {"id":2,"email":"b@x.y"}, {"id":3,"email":"c@x.y"}, {"dept_id":2,"email":"d@x.y"}, {"dept_id":3,"email":"e@x.y"} ] </pre>}}}} === 数组交集 === === 数组拍平 === 样本。 <syntaxhighlight lang="javascript"> const sample = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];</syntaxhighlight> 递归。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ let cup = []; arr.forEach(_ => { if(_ instanceof Array) { cup = cup.concat(clap(_)); } else { cup.push(_); } }); return cup; } console.log(clap(sample));</syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} reduce。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ return arr.reduce((prev, cur)=>{ return prev.concat(Array.isArray(cur) ? clap(cur) : cur); },[]); } console.log(clap(sample));</syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} flat。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ return arr.flat(Infinity); } console.log(clap(sample));</syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} 扩展运算符。有待优化。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ let cup = []; let _sign = true; arr.forEach(_ => { if(Array.isArray(_)) { cup.push(..._); _sign = false; } else { cup.push(_); } }); if(_sign) return cup; return clap(cup); } console.log(clap(sample));</syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} toString。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ return arr.toString().split(',').map(_ => parseInt(_)); } console.log(clap(sample));</syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} apply。 {{leftrightflex|<syntaxhighlight lang="javascript"> function clap(arr){ while(arr.some(_ => Array.isArray(_))){ arr = [].concat.apply([],arr); } return arr; } console.log(clap(sample)); </syntaxhighlight>|{{consoleout|<pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] </pre>}}}} == 清空数组 == {{leftrightflex|<syntaxhighlight lang="javascript"> var arr = [0, 1, 2, 3]; var obj = {val: arr}; arr = []; console.log(JSON.stringify(obj));</syntaxhighlight>|{{consoleout|<pre>{"val":[0,1,2,3]} </pre>}}}} 清空数组 {{leftrightflex|<syntaxhighlight lang="javascript"> var arr = [0, 1, 2, 3]; var obj = {val: arr}; arr.length = 0; console.log(JSON.stringify(obj));</syntaxhighlight>|{{consoleout|<pre>{"val":[]} </pre>}}}} <div class="pageBoxGreen">关键词:引用</div> === 相关问题 === 今天(2021-1-18)视频面试美团的一个岗位,笔试题是数组去重,如输入 <code>[1, 2, 1, 1, '1']</code>,输出 <code>[1, 2, '1' ]</code>,看到题目第一眼我就想起使用 <code>new Set</code>,然后写了如下代码: <syntaxhighlight lang="javascript"> ...new Set(array)</syntaxhighlight> {{leftrightflex|<syntaxhighlight lang="javascript"> console.log([...new Set([1, 2, 1, 1, '1'])]) </syntaxhighlight>|{{consoleout|<pre> VM254:1 (3) [1, 2, "1"] </pre>}}}} 接着试探着问面试官应该可以吧,面试官反应平平(我猜测他可能没用过这种方式,也不知道对不对),我也不好再尝试运行,虽然我知道可以解这道题,但是面试官不确定那我还是老老实实写其他代码吧,然后写了如下: {{leftrightflex|<syntaxhighlight lang="javascript"> function foo(arr){ var map = {} var arr2 = [] for(let i=0;i<arr.length;i++){ if(!map[arr[i]]){ map[arr[i]]=arr[i] } } // 遍历 map for(const key in map){ arr2.push(key) } return arr2 } console.log(foo([1, 2, 1, 1, '1'])) </syntaxhighlight>|{{consoleout|<pre> VM271:15 (2) ["1", "2"] </pre>}}}} 面试官说你看对么,然后我看了一眼发现 <code>Number 1</code> 和 <code>String 1</code> 被等值了,毕竟是 map 是一个 object。我又尝试的问了一下,您觉的这样应该怎么处理呢,面试官说:“你在里面加一下判断,试着把 <code>Number 1</code> 和 <code>String 1</code> 区分开”,我想了一下没什么概念就试探着说其实这里可以用 Map 解决的,只需要把 <code>var map = new Map()</code> 就可以了(我感觉没有我反应快。。。,而且这判断怎么加。。。),面试官无感,我也就没再改代码,然后结束了。事后补全以下代码: {{leftrightflex|<syntaxhighlight lang="javascript"> function foo(arr){ var map = new Map() var arr2 = [] for(let i=0;i<arr.length;i++){ if(!map.get(arr[i])){ map.set(arr[i], arr[i]) } } // 遍历 map for(const [key, value] of map){ arr2.push(key) } return arr2 } console.log(foo([1, 2, 1, 1, '1'])) </syntaxhighlight>|{{consoleout|<pre> VM254:1 (3) [1, 2, "1"] </pre>}}}} == 过滤 == == 多层过滤(多维过滤) == 数组多层过滤,需要注意<code>引用</code>的问题。 <br> 样本数据。 <syntaxhighlight lang="javascript"> [{ "id": 3541, "name": "124", "create_at": "2021-12-26 21:57:41", "group": "124", "artboards": [{ "id": 32211, "name": "one", "checked": false }], "expend": true }, { "id": "null", "group": "未分组", "artboards": [{ "id": 32131, "name": "Toast_icon_prompt@2x", "checked": false }, { "id": 32130, "name": "Toast_icon_prompt@3x", "checked": false }], "name": "未分组" }]</syntaxhighlight> === JSON === <blockquote><pre> JSON.parse(JSON.stringify(foo));</pre></blockquote> <syntaxhighlight lang="javascript"> if (''.indexOf(searchValue) > -1) return setCurrentList(groupList); const groupListTmp = JSON.parse(JSON.stringify(groupList)); const tmpList = groupListTmp.filter(item => { if (item?.artboards?.length) { const queryChildrenNode = item?.artboards.filter(item => (item.name.indexOf(searchValue) != -1)); if (queryChildrenNode.length) { item.artboards = queryChildrenNode; return 1 === 1; } } // if ((item.name?.indexOf(searchValue) != -1)) return 1 === 1; });</syntaxhighlight> == 参考 == * [https://v8.dev/blog/elements-kinds Elements kinds in V8]
此页面嵌入的页面:
模板:Consoleout
(
查看源代码
)
模板:Double-columns
(
查看源代码
)
模板:Double-columns/style.css
(
查看源代码
)
模板:Unknown
(
查看源代码
)
返回
JavaScript/array
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。