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

JavaScript array manipulation to delete odd array elements

本文关键字:数组元素 删除 数组 操作 JavaScript      更新时间:2023-09-26

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

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

我需要从数组中删除所有"废话"部分。

废话总是有一个均匀的索引。

我建议,基于"废话"词总是(如问题中所述)"偶数"元素:

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

引用:

  • Array.prototype.filter() .
  • Array.prototype.indexOf() .
  • JavaScript 正则表达式。
  • RegExp.prototype.test() .
  • String.prototype.indexOf() .
这只是

@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>