【问题标题】:Getting empty array on applying splice. How to fix it?在应用拼接时获取空数组。如何解决?
【发布时间】:2018-12-26 14:14:42
【问题描述】:

在这里,我想在 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"));

【问题讨论】:

  • 您的预期输出是什么?您可以在其中访问许多 console.logs
  • 请阅读splice 的作用。
  • @PhilippSander 预期输出是 ['a', 'b', 'c', 'd', 'test', 'e', 'f', 'g', 'h' ]请运行上面的代码。你会知道的。

标签: javascript arrays typescript replace splice


【解决方案1】:

您的问题是了解Array#splice() 返回的内容

Array#splice() MDN docs

返回:包含已删除元素的数组。如果仅删除一个元素,则返回一个包含一个元素的数组。如果没有元素被移除,则返回一个空数组。


所以先拼接然后记录整个数组以查看结果

let x = "abcdefgh";

let y = x.split('');

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

console.log(y);

【讨论】:

    【解决方案2】:

    如果您要从左侧插入字符

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

    slice() 方法将数组中的选定元素作为新的数组对象返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      相关资源
      最近更新 更多