使用find()通过对象循环数组

时间:2018-04-19 13:27:09

标签: javascript reactjs

int main(int argc, char *argv[]) { int a = 100000, b = 90000; printf("%ld\n%ld\n", product_wrong(a, b), product_right(a, b)); return 0; } long product_wrong(int a, int b) { return (long) (a * b); } long product_right(int a, int b) { return (long) a * b; } 中,我有一个包含3个对象的数组,其值为:1000,2000,3000。我想创建一个函数,当用户输入1和1之间的数字时。 1000你得到了对象

state.1.extras.mileage

当输入介于1000和1000之间时2000你将得到第二个对象, 当你输入2000和3000之间时,你会得到第三个对象。

这是我目前的职能:

        {
          name: '1.000 mileage',
          mileage: '1.000',
          description: 'mileage-description',
        },

1 个答案:

答案 0 :(得分:1)

你有一个包含三个对象的数组,每个对象都有一个里程值。使用javascript find函数,您将获得满足您所声明条件的第一个值。

你的职能:

getObject(speed) {
  const mileage= [
            {
              name: '1000 mileage',
              mileage: '1000',
              description: 'mileage-description',
            },
            {
              name: '2000 mileage',
              mileage: '2000',
              description: 'mileage-description 2',
            },
            {
              name: '3000 mileage',
              mileage: '3000',
              description: 'mileage-description 3',
            }
          ];

  return mileage.find(obj => parseInt(obj.mileage, 10) >= speed);
}

以下代码段:



var speed = [800, 1000, 1001, 995, 2000, 2958, 3000];
console.log(speed);
var getMileage = (speed) => {
  const mileage= [
      {
        name: '1000 mileage',
        mileage: '1000',
        description: 'mileage-description',
      },
      {
        name: '2000 mileage',
        mileage: '2000',
        description: 'mileage-description 2',
      },
      {
        name: '3000 mileage',
        mileage: '3000',
        description: 'mileage-description 3',
      }
    ];
    
    return mileage.find(obj => parseInt(obj.mileage, 10) >= speed);
};

console.log(speed.forEach(s => console.log(s, 'object: ', getMileage(s))));