用于删除奇数数组元素的JavaScript数组操作

时间:2014-11-13 00:10:46

标签: javascript jquery html

我需要帮助;我有一个像这样的数组:

myarray = ["nonsense","goodpart","nonsense2","goodpar2t","nonsense3","goodpart3",]

我需要删除所有"废话"来自阵列的部分。

废话总是有一个偶数索引。

2 个答案:

答案 0 :(得分:13)

我建议,基于“无意义”的词总是(如问题中所述)“偶数”元素:

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
  filtered = myarray.filter(function(el, index) {
    // normally even numbers have the feature that number % 2 === 0;
    // JavaScript is, however, zero-based, so want those elements with a modulo of 1:
    return index % 2 === 1;
  });

console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]

但是,如果您想按数组元素本身进行过滤,则删除包含“废话”一词的所有单词:

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
  filtered = myarray.filter(function(el) {
    // an indexOf() equal to -1 means the passed-in string was not found:
    return el.indexOf('nonsense') === -1;
  });

console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]

或者只查找并保留以'good'开头的单词:

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
  filtered = myarray.filter(function(el) {
    // here we test the word ('el') against the regular expression,
    // ^good meaning a string of 'good' that appears at the beginning of the
    // string:
    return (/^good/).test(el);
  });

console.log(filtered); // ["goodpart", "goodpar2t", "goodpart3"]

参考文献:

答案 1 :(得分:2)

这只是@ DavidThomas的好回答(+1)的一个小变化。如果您决定按值(nonsense)而不是按位置(odd)排除数组成员,这将非常有用:

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
    filtered = myarray.filter(function(el) {
        //return only values that do not contain 'nonsense'
        return el.indexOf('nonsense') === -1;
    });

var myarray = ["nonsense", "goodpart", "nonsense2", "goodpar2t", "nonsense3", "goodpart3"],
  filtered = myarray.filter(function(el) {
    //return only values that do not contain 'nonsense'
    return el.indexOf('nonsense') === -1;
  });


//output result
$('pre.out').text( JSON.stringify( filtered ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre class="out"></div>