[英]Concatenate a string to each element of an array which is not null
I have an array like this: ["name1", "name2", null, null, "name5", null]
我有这样的数组: ["name1", "name2", null, null, "name5", null]
I want to make it like this: 我想这样做:
["name1 wow", "name2 wow", null, null, "name5 wow", null]
I tried to do it like this: 我试着这样做:
myCtrl.myArray.map(s => s + " wow");
Seems it's not the right solution, any ideas? 似乎它不是正确的解决方案,任何想法?
Try Aarry's map()
with the help of ternary operator like the following: 在三元运算符的帮助下尝试Aarry的map()
,如下所示:
var arr = ["name1", "name2", null, null, "name5", null]; var res = arr.map(function(item){ return item != null ? item + ' wow' : null; }); console.log(res);
You could use a logical AND &&
for checking falsy values and return the falsy value direcly or concat the value with a postfix. 您可以使用逻辑AND &&
来检查falsy值并直接返回falsy值或使用postfix连接值。
You need to assign the result array of Array#map
to a new or the old variable. 您需要将Array#map
的结果数组分配给新变量或旧变量。
var array = ["name1", "name2", null, null, "name5", null], result = array.map(s => s && s + " wow"); console.log(result);
只有当s
不为空时才进行添加
myCtrl.myArray.map(s => (s==null?null:s + " wow"));
Add condition for null
checking 添加null
检查条件
let a = ["name1", "name2", null, null, "name5", null]; console.log(a.map(s => s == null ? null : (s + ' wow') ));
For the sake of completeness, you don't actually have to compare to null
: 为了完整起见,您实际上不必与null
进行比较:
var arr = ["name1", "name2", null, null, "name5", null];
var res = arr.map(function(item) {
return item ? item + ' wow' : null;
});
console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.