简体   繁体   English

当我保存方法的返回时,它保存未定义

[英]When I save the return of the method it saves undefined

I've recently started learning JS and in this problem I have to do two methods, the first one creates an array with the cars that haven't been sold yet and the second has to create an array with the cars that haven´t been sold yet and are 0 km.我最近开始学习 JS,在这个问题中我必须做两种方法,第一种方法创建一个包含尚未售出的汽车的数组,第二个必须创建一个包含尚未售出的汽车的数组已售出,距离为 0 公里。 I have to use the first method in the second one, but when I save the return of the first method it saves UNDEFINED.我必须在第二种方法中使用第一种方法,但是当我保存第一种方法的返回时,它会保存 UNDEFINED。 Thanks谢谢

let cars = require('./cars');

let concessionaire = {
  cars: cars,

  carsForSell: function() {
    let carsNotSold = [];
    for (let i = 0; i < this.cars.length; i++) {
      if (this.cars[i].sold == false) {
        carsNotSold.push(this.cars[i]);
      }
    }
    return carsNotSold;
  },

  newCars: function() {
    let aux = this.carsForSell();
    let zeroKm = [];
    for (let i = 0; i < this.cars.length; i++) {
      if (this.aux[i].km < 100) {
        zeroKm.push(aux[i]);
      }
    }
    return zeroKm;
  }
};

The structure of cars is汽车的结构是

let firstCar = {
    brand: 'Ford',
    model: 'Fiesta',
    price: 150000,
    km: 200,
    color: 'Blue',
    dues: 12,
    year: 2019,
    patent: 'APL123',
    sold: false
};

let secondCar = {
    brand: 'Toyota',
    model: 'Corolla',
    price: 100000,
    km: 0,
    color: 'White', 
    dues: 14,
    year: 2019,
    patent: 'JJK116',
    sold: false
};

let cars = [firstCar, secondCar];

module.exports = cars;

The method are correct, you have an additional this in your code:该方法是正确的,您的代码中有一个附加this

 if(this.aux[i].km < 100){

aux is a local variable, this is wrong. aux是一个局部变量, this是错误的。

Working version:工作版本:

 let firstCar = { brand: 'Ford', model: 'Fiesta', price: 150000, km: 200, color: 'Blue', dues: 12, year: 2019, patent: 'APL123', sold: false }; let secondCar = { brand: 'Toyota', model: 'Corolla', price: 100000, km: 0, color: 'White', dues: 14, year: 2019, patent: 'JJK116', sold: false }; let cars = [firstCar, secondCar]; let concessionaire = { cars: cars, carsForSell: function(){ let carsNotSold = []; for (let i = 0; i < this.cars.length; i++){ if(this.cars[i].sold == false){ carsNotSold.push(this.cars[i]); } } return carsNotSold; }, newCars: function(){ let aux = this.carsForSell(); let zeroKm = []; for (let i = 0; i < this.cars.length; i++){ if(aux[i].km < 100){ zeroKm.push(aux[i]); } } return zeroKm; } }; console.log(concessionaire.newCars())

When you declared "concessionaire" there is no variable "cars".当您声明“特许经营权”时,没有变量“汽车”。

If you use let and const scope.如果你使用 let 和 const scope。 you have to write cars first, so that "concessionaire" can use that value.您必须先编写汽车,以便“特许经营权”可以使用该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM