在下面的简单测试代码中,我将数字10推入一个数组,然后将’hello world’拼接到第二个索引上的数组中.它按预期工作.
- "use strict";
- let myArray = [1,2,3,4,5];
- myArray.push(10);
- myArray.splice(2,'hello world');
- console.log(myArray);
但是有可能在一条线上做到这一点吗?我尝试在下面的示例链接,它会抛出一个错误.我找不到有人在网上谈论这个.
- "use strict";
- let myArray = [1,5];
- myArray.push(10).splice(2,'hello world');
- console.log(myArray);
解决方法
如果您使用的是现代JavaScript浏览器,则使用
array spread syntax可以更轻松地推送部件.由于其他人都在使用链接(这需要更改内置的Array对象,我不喜欢),我将使用有些不同:
- "use strict";
- let myArray = [1,5];
- function notSplice(array,start,end,...items) {
- array.splice.apply(array,[start,...items]);
- return array;
- }
- myArray = notSplice([...myArray,10],'hello world');
- console.log(myArray);