最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to apply multiple Array methods to an array in 1 line? - Stack Overflow

programmeradmin1浏览0评论

In the simple test code below I push the number 10 into an array and then splice 'hello world' into the array on the 2nd index. It works as expected.

"use strict";

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

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

console.log(myArray);

In the simple test code below I push the number 10 into an array and then splice 'hello world' into the array on the 2nd index. It works as expected.

"use strict";

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

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

console.log(myArray);

However is it possible to do this on one line? I tried chaining in the example below and it throws an error. I can't find anyone talking about this online.

"use strict";

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

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

console.log(myArray);

Share Improve this question asked Jun 6, 2018 at 19:37 DR01DDR01D 1,36515 silver badges40 bronze badges 3
  • 5 push() returns the new length of the array, not the array itself, so you can't chain it. – Barmar Commented Jun 6, 2018 at 19:39
  • You can override the methods on Array.prototype, but you can't change the return value of push and splice (which would have to be the array) – Alexander Derck Commented Jun 6, 2018 at 19:39
  • 1 As @Francesco alludes to in their answer, what is the benefit of doing this in one line? – CJ Dennis Commented Jun 7, 2018 at 2:43
Add a comment  | 

6 Answers 6

Reset to default 9

Yes, it is possible to do it in one line.

"use strict";

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

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

console.log(myArray);

But why do you want to do that in one line? If your concern is readability I would stick with two lines. If you want it more functional, then use a functional library

edit

I agree with what every one else said about chainability. I'm just trying to make another point

These built-in methods are not designed to be part of a fluent interface, as they don't return the array that they're operating on (push() returns the new length, splice() returns the sub-array that was removed). You could add your own methods that are similar but are fluent.

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);

If you're using a modern JavaScript browser the push part is a little easier, using the array spread syntax. Since everyone else is using chaining (which requires altering the built-in Array object, which I don't like), I'll use something different:

"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);

You could take the methods and parameters in an array and iterate with a function, which take the array as this value.

"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);

Chaining works by calling a method of the return value of the previous method call. For example:

myArray.filter(...).map(...).join(', ').trim()

// is equivalent to

const filteredArray = filtered.map(...)    
const mappedArray = filteredArray.map(...) // filteredArray is an array, we can use map.
const aString = mappedArray.join(', ')     // mappedArray is an array, we can use join
const trimmedString = aString.trim()       // aString is a string, we can use trim

But in your case, it doesn't work because push returns a number (the length of the array plus the new item). There is no splice method for numbers.

myArray.push(...).splice(...)

// is equivalent to doing

const result1 = myArray.push(...)
const result2 = result1.splice(...) // But result1 isn't an array.

This is only possible if the methods you want to chain all return an Array, push returns the length of the array:

console.log([1,2].push(3)) // 3, not an array

console.log([1,2].map(x => x+1)) // [2,3], an array

发布评论

评论列表(0)

  1. 暂无评论