我有一个名称(变量名)列表,在运行其他代码以添加或删除名称后,我想将其放置在名为nameupdated的列表中:
var names = new Array('Alice', 'Bryan', 'Catherine', 'Douglas', 'Emma', 'Frank');
var name = "";
var nameupdated = "";
var text = "";
for(var i in names){
name = names[i];
if (name == "" || name == text || typeof(name) == undefined)
{
}
else{
nameupdated = nameupdated + name + "\n";
}
}
我似乎无法删除最后一个换行符,但是我尝试操纵代码。有什么想法的人吗?
答案 0 :(得分:3)
如果使用.filter
删除要排除的项目,然后使用.join
删除换行符,则逻辑可能会更加清楚。请注意,数组文字通常比使用new Array
构造函数更好:
var text = 'foo';
var names = [
'Alice',
'Bryan',
'Catherine',
'Douglas',
'Emma',
'Frank'
];
var nameUpdated = names
.filter(name => !(name == "" || name == text || typeof(name) == undefined))
.join('\n');
console.log(nameUpdated);
答案 1 :(得分:0)
new line
的字符串,请再试一次
var names = [
'Alice',
'Bryan',
'Catherine',
'Douglas',
'Emma',
'Frank'
];
//Array with \n
var result = [...names].map((d, i) => i < names.length-1 && (name => !(name == "" || name == text || typeof(name) == undefined)) ? d+'\n' : d);
//String with new line after each element
var result1 = [...names].map((d, i) => i < names.length-1 && (name => !(name == "" || name == text || typeof(name) == undefined))? d+'\n' : d).join('');
console.log(result);
console.log(result1);