在下面的简单测试代码中,我将数字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);
发布于 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);
发布于 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);
发布于 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);
https://stackoverflow.com/questions/50728275
复制相似问题