![](/img/trans.png)
[英]4. Define a function with one parameter (position) to find an element by the position stored in the array and to return the details of element found
[英]Return modified array after adding one element at certain position
是否有任何 function在某个索引处插入值并返回修改后的数组,如filter
或map
?
我已经尝试过array.splice(item, 0, index)
但它返回[]
而不是修改后的数组
您可以通过使用Array#flatMap
在索引处返回两个值来在索引处添加一个值
const array = [1, 2, 4, 5], index = 2, newValue = 3, newArray = array.flatMap((v, i) => i === index? [newValue, v]: v); console.log(...newArray);
不,但您可以使用Array.prototype
添加自己的 function :
const arr = ["foo", "bar", "baz"] Array.prototype.spliceReturn = function(idx, val) { this.splice(idx, 0, val) return this } let res = arr.spliceReturn(1, 'biz') console.log(res)
您可以使用splice
添加到数组并返回它:
const insert = (arr, index, val) => { arr.splice(index, 0, val); return arr; } console.log( insert([0,1,3], 2, 2) );
下一种方法更灵活地处理数组项目,无论是单个项目还是多个项目。 它符合验收标准,即 OP 之一和ASDFGerte之一...
function newArrayFromInsertItems(arr, idx, ...items) { arr = Array.from(arr?? []); arr.splice(idx, 0, ...items); return arr; } const arr = ['foo', 'bar', 'baz']; console.log( "newArrayFromInsertItems(arr, 1, 'buz')...", newArrayFromInsertItems(arr, 1, 'buz') ); console.log( "newArrayFromInsertItems(arr, 1, 'biz', 'buz')...", newArrayFromInsertItems(arr, 1, 'biz', 'buz') ); console.log( "newArrayFromInsertItems(arr, 2, ['bar', 'baz'], 'biz')...", newArrayFromInsertItems(arr, 2, ['bar', 'baz'], 'biz') ); console.log('arr...', arr);
.as-console-wrapper { min-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.