简体   繁体   English

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

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

I want to remove all element from array except the element of array at 0th index我想从数组中删除除第 0 个索引处的数组元素之外的所有元素

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

Output should be a Output 应该是a

You can set the length property of the array.您可以设置数组的length属性。

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

OR, Use splice(startIndex) method或,使用splice(startIndex)方法

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

OR use Array.slice method或使用Array.slice方法

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

This is the head function.这是head函数。 tail is also demonstrated as a complimentary function. tail也被证明是一种补充功能。

Note, you should only use head and tail on arrays that have a known length of 1 or more.请注意,您应该只在已知长度为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']

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

You can use splice to achieve this.您可以使用 splice 来实现这一点。

Input.splice(0, 1);

More details here .更多细节在这里。 . . . . http://www.w3schools.com/jsref/jsref_splice.asp http://www.w3schools.com/jsref/jsref_splice.asp

You can use slice:您可以使用切片:

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

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

If you want to keep it in an array , you can use slice or splice .如果你想把它保存在一个array ,你可以使用slicesplice Or wrap the wirst entry again.或者再次包装第一个条目。

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

The shift() method is a perfect choice to do this. shift()方法是执行此操作的完美选择。

var input = ['a','b','c','d','e','f'];  
let firstValue = input.shift();
console.log(firstValue);
var input = ["a", "b", "c", "d", "e", "f"];

[input[0]];

// ["a"]
var output=Input[0]

It prints the first element in case of you want to filter under some constrains如果您想在某些限制下进行过滤,它会打印第一个元素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM