如何从数组中删除除javascript中的第一个元素以外的所有元素

问题描述 投票:18回答:8

我想从数组中删除除第0个索引处的数组元素以外的所有元素

["a", "b", "c", "d", "e", "f"]

输出应为a

javascript arrays slice array-splice
8个回答
46
投票

您可以设置数组的length属性。


5
投票

这是var input = ['a','b','c','d','e','f']; input.splice(1); console.log(input);功能。 head也被证明是一项补充功能。


1
投票
// head :: [a] -> a
const head = ([x,...xs]) => x;

// tail :: [a] -> [a]
const tail = ([x,...xs]) => xs;

let input = ['a','b','c','d','e','f'];

console.log(head(input)); // => 'a'
console.log(tail(input)); // => ['b','c','d','e','f']

1
投票

您可以使用拼接来实现。


1
投票

您可以使用切片:


1
投票

如果要将其保留在https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice中,则可以使用arrayslice。或再次包装愿望条目。


0
投票
var Input = ["a","b","c","d","e","f"];  

console.log( [Input[0]] );
console.log( Input.slice(0, 1) );
console.log( Input.splice(0, 1) );

-2
投票
var input = ["a", "b", "c", "d", "e", "f"];

[input[0]];

// ["a"]
© www.soinside.com 2019 - 2024. All rights reserved.