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

How to remove all element from array except the first one in javascript

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

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

输出应该是a

可以设置数组的length属性

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

或者,使用splice(startIndex)方法

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

或使用Array.slice方法

var input = ['a','b','c','d','e','f'];  
var output = input.slice(0, 1) // 0-startIndex, 1 - endIndex
console.log(output); 

array = [a,b,c,d,e,f];
remaining = array[0];
array = [remaining];

你可以使用 splice 来实现。

Input.splice(0, 1);

此处有更多详细信息。 . .http://www.w3schools.com/jsref/jsref_splice.asp

你可以使用切片:

var input =['a','b','c','d','e','f'];  
input = input.slice(0,1);
console.log(input);

文档:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

如果要将其保留在 array 中,可以使用 slicesplice。或再次包装 wirst 条目。

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

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

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

请注意,您应该只在已知长度为 1 或更长的数组上使用 headtail

// 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']

var output=Input[0]

它会打印第一个元素,以防您想在某些约束下进行过滤

var Input = [ a, b, c, d, e, a, c, b, e ];
$( "div" ).text( Input.join( ", " ) );

Input = jQuery.grep(Input, function( n, i ) {
  return ( n !== c );
});
var input = ["a", "b", "c", "d", "e", "f"];

[input[0]];

// ["a"]