问题
I want to remove all element from array except the element of array at 0th index
["a", "b", "c", "d", "e", "f"]
Output should be a
回答1:
You can set the length
property of the array.
var input = ['a','b','c','d','e','f'];
input.length = 1;
console.log(input);
OR, Use splice(startIndex) method
var input = ['a','b','c','d','e','f'];
input.splice(1);
console.log(input);
OR use Array.slice method
var input = ['a','b','c','d','e','f'];
var output = input.slice(0, 1) // 0-startIndex, 1 - endIndex
console.log(output);
回答2:
This is the head
function. tail
is also demonstrated as a complimentary function.
Note, you should only use head
and tail
on arrays that have a known length of 1 or more.
// 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']
回答3:
array = [a,b,c,d,e,f];
remaining = array[0];
array = [remaining];
回答4:
You can use splice to achieve this.
Input.splice(0, 1);
More details here . . .http://www.w3schools.com/jsref/jsref_splice.asp
回答5:
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
回答6:
If you want to keep it in an array
, you can use slice
or splice
. 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) );
回答7:
var input = ["a", "b", "c", "d", "e", "f"];
[input[0]];
// ["a"]
回答8:
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 );
});
来源:https://stackoverflow.com/questions/39510821/how-to-remove-all-element-from-array-except-the-first-one-in-javascript