如何从数组中删除除JavaScript中的第一个元素以外的所有元素 [英] How to remove all element from array except the first one in javascript

查看:1102
本文介绍了如何从数组中删除除JavaScript中的第一个元素以外的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to remove all element from array except the element of array at 0th index

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

输出应为a

推荐答案

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

You can set the length property of the array.

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

或者,使用 splice(startIndex) 方法

OR, Use splice(startIndex) method

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

这篇关于如何从数组中删除除JavaScript中的第一个元素以外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆