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

sha*_*077 14 javascript arrays slice array-splice

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

["a", "b", "c", "d", "e", "f"]
Run Code Online (Sandbox Code Playgroud)

输出应该是 a

Sat*_*pal 32

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

var input = ['a','b','c','d','e','f'];  
input.length = 1;
console.log(input);
Run Code Online (Sandbox Code Playgroud)

或,使用splice(startIndex)方法

var input = ['a','b','c','d','e','f'];  
input.splice(1);
console.log(input);
Run Code Online (Sandbox Code Playgroud)

  • 我对“input.length = 1”解决方案感到惊讶。我认为 `length` 是只读属性:) (2认同)

Tha*_*you 5

这就是head函数。tail也被证明是一个补充功能。

请注意,您只能在已知长度为1head或更大的数组上使用and 。tail

// 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']
Run Code Online (Sandbox Code Playgroud)