简体   繁体   English

如何将实例重写为 function?

[英]How do I rewrite an instantiation to a function?

I would like to have a function called getSelectedValues which retrieves data from the options array instead of a variable called SelectedValues ( which is the way I have it now).我想要一个名为 getSelectedValues 的 function ,它从选项数组而不是名为 SelectedValues 的变量中检索数据(这是我现在拥有的方式)。 The variable Selected Values currently gets the values that are true inside of the options array and assigns them to itself.变量 Selected Values 当前获取选项数组中为 true 的值并将它们分配给自身。 I simply would like to make this a function instead.我只是想让它成为 function 。 (something called getSelectedValues I would imagine) How do I achieve this? (我会想象称为 getSelectedValues 的东西)我如何实现这一目标?

var options = [
{
name: "Red Pepper",
"selected": false,
value: "5.99"   
},
  {
name: "Garlic",
"selected": true,
value: "5.99"   
},
      {
name: "Tomatoes",
"selected": true,
value: "5.99"   
}, 
]


  var SelectedValues = options.filter(function (option) {
  return (option.selected);
  });
 console.log(SelectedValues)

Just for reference, read more:仅供参考,阅读更多:

Declaring functions in JavaScript 在 JavaScript 中声明函数

function filterOptions(options) {
  return options.filter(i => i.selected);
}

 function filterOptions(options) { return options.filter((i) => i.selected); } var options = [ { name: "Red Pepper", selected: false, value: "5.99", }, { name: "Garlic", selected: true, value: "5.99", }, { name: "Tomatoes", selected: true, value: "5.99", }, ]; var selectedValues = filterOptions(options); console.log(selectedValues);
 .as-console { min-height: 100%;important. }:as-console-row { color; blue !important; }

Something like this?像这样的东西?

function getSelectedValues(options) {
  const size = Object.keys(options).length;
  for (var i = 0; i < size; i = i + 1) {
    const isSelected = options[i]["selected"];
    if (isSelected) {
      alert(options[i].name);
    }
  }
}

Jsfiddle here: https://jsfiddle.net/z3nrh8Ly/50/ Jsfiddle在这里: https://jsfiddle.net/z3nrh8Ly/50/

function getSelectedValues() {
   return options.filter(t => t.selected);

}

another way:另一种方式:

getSelectedValues = () => options.filter(t => t.selected);

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

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