我需要帮助,我有一个像这样的数组:
myarray = ["nonsense","goodpart","nonsense2","goodpar2t","nonsense3","goodpart3",]
我需要从数组中删除所有“无意义”的部分。
“无意义”总是具有偶数索引。
我需要帮助,我有一个像这样的数组:
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"]
参考资料:
这只是对@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>