And*_*tis 2 html javascript jquery
我需要帮助; 我有这样一个数组:
myarray = ["nonsense","goodpart","nonsense2","goodpar2t","nonsense3","goodpart3",]
Run Code Online (Sandbox Code Playgroud)
我需要从数组中删除所有"废话"部分.
废话总是有一个偶数索引.
Dav*_*mas 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"]Run Code Online (Sandbox Code Playgroud)
但是,如果您希望按数组元素本身进行过滤,则删除包含"无意义"一词的所有单词:
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"]Run Code Online (Sandbox Code Playgroud)
或者只查找并保留以下开头的单词'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"]Run Code Online (Sandbox Code Playgroud)
参考文献:
Array.prototype.filter().Array.prototype.indexOf().RegExp.prototype.test().String.prototype.indexOf().