箭头功能评估

时间:2018-04-24 15:45:09

标签: javascript reactjs react-native eslint

我是箭头函数的新手,我只是在没有未定义时才尝试添加到数组但我无法弄清楚语法。我应该如何写下面的if语句?谢谢!

let carList = cars.map(car => (
  if(car.owner !== "undefined"){ // this is the condition I want.
  do something
 }
));

3 个答案:

答案 0 :(得分:3)

与任何其他函数一样,正文必须是大括号,而不是括号:

let carList = cars.map(car => {
   // code here
});

请记住map()为原始数组中的每个元素创建一个新元素。如果您只想对列表中的某些元素执行操作,则应首先使用filter()

let carList = cars.filter(car => {
   return car.owner !== undefined
}).map(car => {
   // Do something to each car
});

请注意,undefined是一个关键字,不需要引号。使用字符串值"undefined",虽然合法,但可能令人难以置信的混淆,所以我建议反对它。

答案 1 :(得分:1)

听起来你需要filter而不是map



const cars = [
  { owner: '', age: 12 },
  { owner: 'bob', age: 1 },
  { owner: undefined, age: 2 },
  { owner: 'steve', age: 13 },
  { age: 1 }
];

let carList = cars.filter(car => car.owner);

console.log(carList);




答案 2 :(得分:0)

如果您想通过字符串进行比较,则需要添加typeof 另外,用大括号括起函数。

let carList = cars.map(car => {
  if(typeof(car.owner) !== "undefined"){ // this is the condition I want.
  do something
 }
});

或抛弃字符串引号

let carList = cars.map(car => {
  if(car.owner !== undefined){ // this is the condition I want.
  do something
 }
});

或者只使用布尔值而不是。

let carList = cars.map(car => {
  if(!car.owner){ // this is the condition I want.
  do something
 }
});

let cars = [{},{owner:'foo'},{owner:'bar'}, {fun:'none'}];
let carList = cars.map(car => {
  if(!car.owner){ // this is the condition I want.
    console.log(car,'has no owner');
 }}
);

相关问题