gpt4 book ai didi

javascript - 如何使用 javascript 识别数组中的自定义值?

转载 作者:行者123 更新时间:2023-11-29 17:36:33 25 4
gpt4 key购买 nike

我做了一个调查,受访者有一个选择题,比方说:“你最喜欢的水果是什么?”,他们可以从列表中随意选择,也可以引入自定义值以防他们想要添加未列出的水果。该列表有以下选项:apple、pear、banana、strawberry 和“custom”。

我需要制作一个包含信息的图表来计算有多少人选择了每种水果。但我会将所有自定义值添加到一个名为“自定义”的值中。假设我最终得到了这样一个数组:

[
{
"Person": "Person1",
"Fruits": [ "apple", "banana", "peach" ]
},
{
"Person": "Person2",
"Fruits": [ "apple", "pear", "strawberry", "coconut" ]
},
{
"Person": "Person3",
"Fruits": [ "pear", "strawberry" ]
},
{
"Person": "Person4",
"Fruits": [ "strawberry", "orange" ]
}
]

为了计算已经列出的水果,我开始使用 includes(),但 IE 不支持它。所以我正在使用我找到的代码 Alternative of .includes() in Internet Explorer .

我的代码:
我为数组中的每个元素创建了一个循环,如果它包含某个单词,它就会存储在对应的数组中:

//I am calling the info with AngularJS don't know if is important to know that
//Declare empty arrays for each fruit
var dataResults = $scope.items, //<---- this is the array with the info, the one I showed before..
apple = [],
pear = [],
banana = [],
strawberry = [],
custom = [];

//function to read if an array includes a certain value
function includes(container, value) {
var returnValue = false;
var pos = container.indexOf(value);
if (pos >= 0) {
returnValue = true;
}
return returnValue;
}

//Loop the survey results
for(var i=0; i<dataResults.length; i++) {
var currentItem = dataResults[i];
//I push the name of the person if he/she chose apple
if(includes(currentItem.Fruits, "apple")){
apple.push(currentItem.Person);
}
//I push the name of the person if he/she chose pear
if(includes(currentItem.Fruits, "pear")){
pear.push(currentItem.Person);
}
//I push the name of the person if he/she chose banana
if(includes(currentItem.Fruits, "banana")){
banana.push(currentItem.Person);
}
//I push the name of the person if he/she chose strawberry
if(includes(currentItem.Fruits, "strawberry")){
strawberry.push(currentItem.Person);
}
};
//now I wanna see the results in the console for each array
console.log("apple: " + apple.length);
console.log("pear: " + pear.length);
console.log("banana: " + banana.length);
console.log("strawberry: " + strawberry.length);

但现在我不知道有多少人输入了自定义值。他们写什么并不重要(因为可能有数百个不同的值),但我需要将它们全部存储为“自定义”。
如何计算未出现在列表中的值?
请帮忙。

最佳答案

看起来是 switch 的不错选择给我的声明。

您还可以删除使用 includes() 的需要。

例如:

//Loop the survey results
var currentItem, f, max;
for(var i=0; i<dataResults.length; i++) {
currentItem = dataResults[i];
max = currentItem.Fruits.length;
for(f=0;f<max;f++) {
switch(currentItem.Fruits[f]) {
case "apple" :
apple.push(currentItem.Person);
break;
case "pear" :
pear.push(currentItem.Person);
break;
case "banana" :
banana.push(currentItem.Person);
break;
case "strawberry" :
strawberry.push(currentItem.Person);
break;
default :
custom.push(currentItem.Person);
}
}
}

关于javascript - 如何使用 javascript 识别数组中的自定义值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com