应用拼接时得到空数组。如何解决?

Getting empty array on applying splice. How to fix it?

这里我想在x长度之前的最后4个字母处添加单词。所以我将字符串转换为数组。应用分裂。但是当我尝试拼接时。在将第二个参数添加到拼接时获取空字符串。寻求帮助。

let x = "abcdefgh";
console.log(x);
console.log(x.length);
let y = x.split('');
console.log(y);
let len = (y.length - 4);
console.log(len);
console.log(y.splice(len));
console.log(y.splice(len, 0, "test"));

你的问题是理解什么 Array#splice() returns

Array#splice() MDN docs

Returns: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.


所以先拼接然后记录整个阵列以查看结果

let x = "abcdefgh";

let y = x.split('');

let len = (y.length - 4);
y.splice(len, 0, "test");

console.log(y);

如果您要从左侧的字符插入

console.log([x.slice(0,4), wordtoBeinserted, x.slice(4)].join(''));

slice()方法returns选中数组中的元素,作为一个新的数组对象。