我想从数组中删除除了第0个元素以外的所有元素
["a", "b", "c", "d", "e", "f"]
输出应该是 a
我想从数组中删除除了第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);
length
是只读属性 :) - Takeshi Tokugawa YD这是 head
函数。 tail
也作为补充函数演示。
请注意,应仅在已知长度为1或更多的数组上使用 head
和 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']
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
数组
中,可以使用slice
或splice
。或者再次包装第一个条目。
var Input = ["a","b","c","d","e","f"];
console.log( [Input[0]] );
console.log( Input.slice(0, 1) );
console.log( Input.splice(0, 1) );
array = [a,b,c,d,e,f];
remaining = array[0];
array = [remaining];
array = [array[0]]
- Geza Kerecsenyishift()
方法是实现此目的的完美选择。
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]
如果您想在某些限制条件下进行过滤,它会打印第一个元素
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 output = Input[0];
- Mairaj AhmadInput.slice().splice(1)
。如果你不关心原始数组,可以使用Input.splice(1)
。 - Sebastian Simon