JavaScript数组操作:删除奇数数组元素

3

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

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

我需要从数组中删除所有“无意义”的部分。
“无意义”总是具有偶数索引。
2个回答

14

基于问题中所述的“胡言乱语”单词总是“偶数”元素的情况,我建议:

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"]

如果您想按照数组元素本身进行过滤,以删除所有包含单词'nonsense'的单词:

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"]

参考资料:


嗯嗯…现在我明白了,为什么会有咳咳…有趣! :) - PeterKA
抱歉,我刚意识到我没有展示其他(可能实用/相关)的方法。我想当你在写自己的答案时,我正在更新。不过,这并不是不点赞的理由 :) - David Thomas

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接