简体   繁体   English

从打字稿中指定位置的数组中添加元素

[英]Add elements to an array from specified position in typescript

I am adding elements to array arr1 using map function. 我正在使用map函数将元素添加到数组arr1 Is there any way to specify the index of starting position in typescript 有什么办法可以指定typescript中起始位置的索引

eg If I want to add elements from 3rd index position of the array. 例如,如果我想从数组的第三个索引位置添加元素。 first two index should hold 0. how can I do that? 前两个索引应保持0。该怎么办?

 let years = [0,1,2,3,4]; data = { var1: 100000, arr2: years.map(_ => 1000) }; console.log(data.arr2); 

I want to add 0 from starting of the array. 我想从数组的开头添加0。 If I specify position as 3 then first 2 element should be zero 如果我将位置指定为3,则前2个元素应为零

You can use array#map and for all index value lower than your desired index place 0 other get the value from your array. 您可以使用array#map ,对于所有低于所需索引位置的索引值,其他0则从数组中获取值。

 let years = [0,1,2,3,4], index = 2, result = years.map((v,i) => i < index ? 0 : v); console.log(result); 

I'm not sure if I understood what you want : 我不确定我是否了解您想要什么:

 let years = [0,1,2,3,4]; data = { var1: 100000, arr2: modifyArray(3, 100000) }; console.log(data.arr2); function modifyArray(position = 0, value) { const newArray = []; for (let i = 0; i < position - 1; i++) { newArray.push(0); } return [...newArray, ...years.slice(0, position ), value, ...years.slice(position)]; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM