在数组数据中插入字符

时间:2019-06-22 11:26:41

标签: node.js typescript

如何从数组中插入字符?

这是我的数据:

var scr = {
    width: window.screen.width,
    height: window.screen.height //... }
JSON.stringify(scr); // --> "{"width":1600,"height":900, ...

我想这样更改我的数据:

["a", "b", "c", ...]

谢谢

2 个答案:

答案 0 :(得分:1)

let a = ["a", "b", "c", ...]
a.map(value => '$'+value) // this will do what you need returns ["$a", "$b", "$c"]

地图基本上遍历数组,并根据给定条件映射每个元素

Array.map(value => 在此处使用任何类型的数据映射值

答案 1 :(得分:0)

使用map- ES6方法

Map mdn

const arr = ['a', 'b']
const modifiedArray = arr.map(el => '$' + el)
console.log(modifiedArray)

不过请注意,它将修改原始数组,因此,如果您不想修改原始array

使用ES6的spread

spread mdn

const modifiedArray = {...arr}.map(el => '$' + el)

非ES6

var arr = ['a', 'b'],
  modifiedArr = []
  
for(let i=0; i < arr.length; i++) {
  modifiedArr.push('$' + arr[i])
}

console.log(modifiedArr)