使用映射将数字数组转换为字符串数组

convert array of numbers in array of strings using map

我正在使用 lodash,我正在尝试转换字符串中的数字数组,但只转换数字,因为我的数组中有空值。我尝试在 javascript 的地图中使用 lodash 地图,但弄乱了空值。

数组示例: [1245, 5845, 4585, 空, 空]

代码:

var meds = _.map(lines,'med_id').map(String);

结果:["1245", "5845", "4585", "null", "null"];

应该是:["1245", "5845", "4585", null, null];

那是因为 String 会将它需要的任何内容转换为字符串。您需要制作一个自定义函数,该函数仅在值不为空时生成字符串。

_.map(lines, 'med_id').map(function(x) {
  if (x !== null) {
    x = x.toString();
  }
  return x;
});

调用前需要先测试值的类型String

var meds = _.map(lines, 'med_id').map(function(x) {
    return typeof x == 'number' ? String(x) : x;
});

在看:https://lodash.com/docs#map

看起来像:

function toInts(n){
    if(isNaN(n)){
       return null;
    }else{
      return n;
    }
}
_.map(lines,'med_id').map(lines,toInts);

就可以了。 (未测试)