JavaScript 数组操作以删除奇数数组元素
JavaScript array manipulation to delete odd array elements
我需要帮助;我有一个这样的数组:
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>
相关文章:
- 从组件状态的数组中删除元素
- Mongoose-在更新中删除数组元素
- 从数组中删除元素的最佳方法是:javascript/jquery
- 一些元素没有从数组中删除
- 从角度数组中删除元素
- 删除仅空格数组元素
- 正在从元素可能不同的数组中删除重复的元素
- 使用 V8 从密集数组中删除元素的最佳方法是什么
- 根据成员属性从数组中删除元素
- 如何从数组中删除元素
- 从数组中删除元素,然后保留其状态以备将来使用,而不使用全局变量
- 删除数组元素并将它们添加回原来的位置
- AngularJS/JavaScript从Localstorage数组中删除特定元素
- 正在从ReactJS数组中删除Stateful元素
- 删除基于另一个数组的数组元素
- 如何从数组中删除元素
- 取消选择下拉项时从数组中删除元素
- 如果一个键匹配,如何删除数组元素
- 从AngularJS中的数组中删除元素时出错
- 通过与猫鼬中的不同数组匹配,从嵌入数组中删除元素