【问题标题】:How to remove all element from array except the first one in javascript如何从数组中删除除javascript中的第一个元素之外的所有元素
【发布时间】:2017-01-23 11:06:35
【问题描述】:

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

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

输出应该是a

【问题讨论】:

  • var output = Input[0];
  • 或者Input.slice().splice(1),如果你真的想要一个数组。如果您不关心原始数组,请使用Input.splice(1)
  • 好的,我的要求是,我必须实现一个名为 remove tab 的功能,该功能从 tabset 数组中删除所有选项卡,除了 home 选项卡,它是第 0 个索引处的选项卡。
  • 这些“标签”实际上是一些 HTML 元素吗?

标签: javascript arrays slice array-splice


【解决方案1】:

您可以设置数组的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); 

【讨论】:

  • 我对@9​​87654328@ 解决方案感到惊讶。我认为length 是只读属性:)
【解决方案2】:
var input = ["a", "b", "c", "d", "e", "f"];

[input[0]];

// ["a"]

【讨论】:

  • 嘿,你应该解释一下你的答案。你背后的想法是什么?也可以在发布之前先完整地写下我们的答案;)
  • @WolverinDEV 你能解释一下否决票吗?我偶然发现了这篇文章,并读到其中两个顶级解决方案使用了拼接和切片。我提供了一个所需字符最少的解决方案...
【解决方案3】:

这是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']

【讨论】:

    【解决方案4】:
    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 );
    });
    

    【讨论】:

      【解决方案5】:

      如果您想将其保存在array 中,可以使用slicesplice。或者再次包装第一个条目。

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

      【讨论】:

        【解决方案6】:

        你可以使用切片:

        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

        【讨论】:

          【解决方案7】:

          您可以使用 splice 来实现这一点。

          Input.splice(0, 1);
          

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

          【讨论】:

            【解决方案8】:
            array = [a,b,c,d,e,f];
            remaining = array[0];
            array = [remaining];
            

            【讨论】:

            • 或者只是array = [array[0]]
            猜你喜欢
            • 1970-01-01
            • 2013-09-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多