-3

在编程方面,我是一个初学者,目前遇到了问题。我有一个包含 4 个项目的数组(您可以在下面的代码部分看到数组),并且所有四个项目都有其特定的 id (1-4)。

我想要编程的东西是一种为每个数组项运行单独代码的方法。我想我可以通过制作 if 语句来解决这个问题,我只需检查 id (每个项目都是单独的)。但我该怎么做?

如果有人有更好的主意,他可以肯定地告诉我那个 id。

最好的问候约翰。

{ id: 1, name: 'BMW', price: 250, quantity: ''},

{ id: 2, name: 'Google', price: 110, quantity: ''},

{ id: 3, name: 'Apple', price: 1000, quantity: ''},

{ id: 4, name: 'Twitter', price: 50, quantity: ''}
4

4 回答 4

0

循环并使用所需的文本比较每个项目的 id filter()- 请注意,然后我可以返回关联的对象(例如 - 如果您想显示名称) - 或者如果它不存在则返回文本字符串。

您还可以在其中添加逻辑以确保 id 是唯一的 - 即,如果为给定的 n id 找到多个结果 - 那么您需要编辑重复项的 id。

let items = [
  { id: 1, name: 'BMW', price: 250, quantity: ''},
  { id: 2, name: 'Google', price: 110, quantity: ''},
  { id: 3, name: 'Apple', price: 1000, quantity: ''},
  { id: 4, name: 'Twitter', price: 50, quantity: ''}
]

function findItem(id){
  
  var foundItem = items.filter(function(item){
    return(item.id == id) 
   });
   
   if(foundItem.length > 0) {
    return foundItem[0];
   } else {
    return "Item not found";
   }
}

console.log(findItem('1')); // returns the object of the BMW
console.log(findItem('6')); // returns "Item not found"

于 2018-12-26T11:52:56.080 回答
0

据我了解,您希望为数组中的不同项目运行单独的代码段。如果数组的元素是固定的,即它们不会改变,那么您可以为每个项目编写不同的代码段作为函数并将其作为属性添加到相应的项目。

请参见下面的示例:

let BMWFunction = function(){
   console.log('BMW!');
}

let googleFunction = function(){
   console.log('Google!');
}

let myArray = [
   { id: 1, name: 'BMW', price: 250, quantity: '', code: BMWFunction},
   { id: 2, name: 'Google', price: 110, quantity: '', code: googleFunction }
]

for (let i = 0; i < myArray.length; i++){
   myArray[i].code();
}

然后对于您在数组中循环的每个项目,您可以调用关联的代码属性。

于 2018-12-26T11:56:31.407 回答
0

您可以使用 if 语句实现此目的。对此有不同的方法,但基本方法将保持不变。循环遍历数组中的每个元素,然后检查 id。您可以使用传统的 for 循环,也可以使用somefilter等方法。

于 2018-12-26T11:41:01.160 回答
0

您可以使用简单的 for 循环简单地迭代您的数组并检查 id 是否等于给定的 id 然后返回整个对象。如果 id 不匹配,它将返回undefined。考虑以下代码片段:

let array = [{ id: 1, name: 'BMW', price: 250, quantity: ''},

{ id: 2, name: 'Google', price: 110, quantity: ''},

{ id: 3, name: 'Apple', price: 1000, quantity: ''},

{ id: 4, name: 'Twitter', price: 50, quantity: ''}];

function getValue(id)
{
  for( var index=0;index<array.length;index++){
     if( array[index].id === id){
        return array[index];
     }
  };
}

console.log(getValue(1));
console.log(getValue(5));

于 2018-12-26T11:43:23.130 回答