首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有没有办法在一行中将多个Array方法应用到一个数组中?

有没有办法在一行中将多个Array方法应用到一个数组中?
EN

Stack Overflow用户
提问于 2018-06-07 03:37:46
回答 5查看 1.8K关注 0票数 8

在下面的简单测试代码中,我将数字10 push到一个数组中,然后将“hello world”splice到第二个索引上的数组中。它的工作方式与预期一致。

"use strict";

let myArray = [1, 2, 3, 4, 5];

myArray.push(10);
myArray.splice(2, 0, 'hello world');

console.log(myArray);

但是,是否可以在一行代码中完成此操作?我在下面的示例中尝试了链接,但它抛出了一个错误。我找不到任何人在网上谈论这件事。

"use strict";

let myArray = [1, 2, 3, 4, 5];

myArray.push(10).splice(2, 0, 'hello world');

console.log(myArray);

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-06-07 04:09:41

如果您使用的是现代的JavaScript浏览器,则使用array spread syntax时,push部件会更简单一些。由于其他人都在使用链接(这需要更改内置的Array对象,我不喜欢这样),所以我将使用一些不同的东西:

"use strict";

let myArray = [1, 2, 3, 4, 5];

function notSplice(array, start, end, ...items) {
  array.splice.apply(array, [start, end, ...items]);
  return array;
}

myArray = notSplice([...myArray, 10], 2, 0, 'hello world');

console.log(myArray);

票数 2
EN

Stack Overflow用户

发布于 2018-06-07 03:44:50

这些内置方法不是fluent接口的一部分,因为它们不返回正在操作的数组(push()返回新的长度,splice()返回被移除的子数组)。您可以添加您自己的类似但流畅的方法。

Array.prototype.mypush = function(...args) {
  this.push(...args);
  return this;
};
Array.prototype.mysplice = function(...args) {
  this.splice(...args);
  return this;
}

let myArray = [1, 2, 3, 4, 5];

myArray.mypush(10).mysplice(2, 0, 'hello world');

console.log(myArray);

票数 3
EN

Stack Overflow用户

发布于 2018-06-07 04:47:50

您可以获取数组中的方法和参数,并使用函数迭代,该函数将数组作为this值。

"use strict";

function arrayFn([k, ...a]) { this[k](...a); }

let myArray = [1, 2, 3, 4, 5];

[
    ['push', 10],
    ['splice', 2, 0, 'hello world']
].forEach(arrayFn, myArray);

console.log(myArray);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50728275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档