Phi*_*ppe 24 javascript arrays
我有一个阵列[a, b, c].我希望能够给此阵列的像的各元件之间的插入值:[0, a, 0, b, 0, c, 0].
我想这会是这样的,但我不能让它奏效.
for (let i = 0; i < array.length; i++) {
newArray = [
...array.splice(0, i),
0,
...array.splice(i, array.length),
];
}
Run Code Online (Sandbox Code Playgroud)
感谢你们对我的帮助!
Nin*_*olz 16
为了获得一个新数组,您可以连接该部分,为每个元素添加一个零元素.
var array = ['a', 'b', 'c'],
result = array.reduce((r, a) => r.concat(a, 0), [0]);
console.log(result);Run Code Online (Sandbox Code Playgroud)
使用相同的数组
var array = ['a', 'b', 'c'],
i = 0;
while (i <= array.length) {
array.splice(i, 0, 0);
i += 2;
}
console.log(array);Run Code Online (Sandbox Code Playgroud)
从末尾开始迭代有点短.
var array = ['a', 'b', 'c'],
i = array.length;
do {
array.splice(i, 0, 0);
} while (i--)
console.log(array);Run Code Online (Sandbox Code Playgroud)
小智 8
如果要排除数组的开始和结束,另一种方法是:
var arr = ['a', 'b', 'c']
var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))
console.log(newArr)Run Code Online (Sandbox Code Playgroud)
您可以使用map()ES6 扩展语法和concat()
var arr = ['a', 'b', 'c']
var newArr = [0].concat(...arr.map(e => [e, 0]))
console.log(newArr)Run Code Online (Sandbox Code Playgroud)
另一个使用flatmap的 ES6+ 版本(如果可以创建新数组):
['a', 'b', 'c', 'd']
.flatMap((e, index) => index ? [e, 0] : [0, e, 0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11118 次 |
| 最近记录: |