嗨,我有这个测试数据,我希望得到像这样的结果
na ===> not available
error ===> error
ok ===> ok
arr1 = ['na','na','ok','ok','na'] => na
arr2 = ['ok','ok','ok','ok','error'] => error
arr2 = ['ok','ok','ok','ok','ok'] => ok
答案 0 :(得分:0)
使用elseif或开关确定数组中是否存在“na”或“error”。
逻辑基于“na”或“error”的第一个实例,将数组设置为该类型。不确定逻辑是否应该找到所有实例,然后根据na / error的总数/最大数设置状态。
编辑 - 我添加了一个switch语句选项来演示该路径 - 请注意,该开关的触发器是hte indexOf()表达式的结果,而不是字符串的存在。
arr1 = ['na','na','ok','ok','na'];
arr2 = ['ok','ok','ok','ok','error'];
arr3 = ['ok','ok','ok','ok','ok'];
function checkArray(arr) {
if ( arr.indexOf('na') !== -1 ) {
return "na";
} else if(arr.indexOf('error') !== -1) {
return "error";
} else {
return "ok";
}
}
console.log("Using an elseif block")
console.log(checkArray(arr1)); // gives 'na'
console.log(checkArray(arr2)); // gives 'error'
console.log(checkArray(arr3)); // gives 'ok'
function checkArray2(arr) {
switch(true) {
case arr.indexOf('na') !== -1:
return "na"
break;
case arr.indexOf('error') !== -1:
return "error"
break;
default:
return "ok"
}
}
console.log(" ")
console.log("Using a switch statement")
console.log(checkArray2(arr1)); // gives 'na'
console.log(checkArray2(arr2)); // gives 'error'
console.log(checkArray2(arr3)); // gives 'ok'
答案 1 :(得分:0)
假设您希望结果element
在[{1}}中出现的次数更多,这可能会有所帮助:
array
答案 2 :(得分:0)
arr1 = ['na', 'na', 'ok', 'ok', 'na'];
arr2 = ['ok', 'ok', 'ok', 'ok', 'error'];
arr3 = ['ok', 'ok', 'ok', 'ok', 'ok'];
function count(arr) {
var na_count = arr.filter(function(a) {return a === 'na';}).length;
var error_count = arr.filter(function(a) {return a === 'error';}).length;
var ok_count = arr.filter(function(a) {return a === 'ok'; }).length;
var length = arr.length
if (length === ok_count) {
return 'ok';
}else if (na_count > error_count) {
return 'na';
}else {
return 'error';
}
}
console.log('using arr1', count(arr1))
console.log('using arr2', count(arr2))
console.log('using arr3', count(arr3))