我正在尝试将以'N'开头的列表元素整理成新列表。 为什么这不起作用?
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
function firstN(){
for (let i=0;i<countries.length;i++){
countries[i].startsWith("N")
}
}
let startsWithN = countries.filter(firstN())
答案 0 :(得分:6)
这与@ adeneo的答案大致相同,只是一点点:
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
const startsWithN = countries.filter((country) => country.startsWith("N"));
console.log(startsWithN);
// Output: [ 'Norway', 'New Zealand' ]
答案 1 :(得分:1)
您根据条件进行过滤,指定的函数会根据该条件返回true
或false
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
function firstN(item) {
return item.toLowerCase().indexOf('n') === 0;
}
let startsWithN = countries.filter(firstN);
console.log(startsWithN)
&#13;
答案 2 :(得分:1)
非常简单:
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
let startsWithN = countries.filter(function (country) {
return country[0].toLowerCase() === 'n';
});
console.log(startsWithN)
&#13;
答案 3 :(得分:0)
countries.filter(s => s.toLowerCase().indexOf("n") == 0)
答案 4 :(得分:0)
如果预期结果是一个新数组,其中只包含以countries
开头的"N"
元素,则可以调整现有javascript
以在firstN
内创建数组,并传递输入数组到firstN
,.push()
元素,在if
循环中将for
条件循环到新数组return
新数组
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
function firstN(arr, letter) {
for (let i = 0, res = []; i < arr.length; i++) {
if (arr[i].startsWith(letter)) res.push(arr[i])
}
return res
}
let startsWithN = firstN(countries, "N");
console.log(startsWithN);
&#13;
要对原始数组进行排序,您可以使用.sort()
。
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
function sortByFirstLetter(letter) {
return function(a, b) {
let [firstLetterA, firstLetterB] = [a[0], b[0]];
return firstLetterA === letter && firstLetterB !== letter ? -1 : 1
}
}
countries.sort(sortByFirstLetter("N"));
console.log(countries);
&#13;
答案 5 :(得分:0)
仍然很苛刻:
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
const startsWithN = countries.filter(/./.test.bind(/^N/));
console.log(startsWithN);
这将函数传递给filter
RexExp.prototype.test
的curry版本:它将上下文(this
)设置为/^N/
,即匹配的正则表达式以大写字母N开头的字符串。结果类似于:
const startsWithN = countries.filter(country => /^N/.test(country));
答案 6 :(得分:0)
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];
const startsWithN = countries.filter((country) => country[0]==='N');
console.log(startsWithN);
答案 7 :(得分:0)
const freinds = ['Salman', 'Asad', 'Shahrukh', 'Aman'];
const startsS = freinds.filter((freind) => freind.startsWith("s"));
console.log(startsS);
输出:
<块引用>['萨尔曼','沙鲁克']