我想在提交表单之前检查是否有任何空白字段。但是问题是我有可变数量的字段(值1,值2 ...),所以我不能使用简单的if语句。
所以我有什么办法可以存档它。
state1 = {
vale1:'',
vale2:'',
vale3:'',
vale4:''
}
state2 = {
vale1:'21',
vale2:'a',
vale3:'f',
vale4:''
}
state3 = {
vale1:'fdf',
vale2:'fgf',
vale3:'gf',
vale4:'hg'
}
state4 = {
vale1:'21',
vale2:'a',
vale3:'f'
}
functionIWant(state1) ----> false
functionIWant(state2) ----> false
functionIWant(state3) ----> true
functionIWant(state4) ----> true
是否有functionIWant
吗?
答案 0 :(得分:4)
您可以获取值并使用布尔值检查每个值。
function check(object) {
return Object.values(object).every(Boolean);
}
var state1 = { vale1: '', vale2: '', vale3: '', vale4: '' },
state2 = { vale1: '21', vale2: 'a', vale3: 'f', vale4: '' },
state3 = { vale1: 'fdf', vale2: 'fgf', vale3: 'gf', vale4: 'hg' },
state4 = { vale1: '21', vale2: 'a', vale3: 'f' };
console.log(check(state1)); // false
console.log(check(state2)); // false
console.log(check(state3)); // true
console.log(check(state4)); // true
答案 1 :(得分:2)
您可以使用JavaScript的foreach
版本并检查是否有任何键值对具有空值或空值:
functionIWant(state){
//boolean to return from function, initialize to true
let notEmpty = true;
//Iterate the state object passed in and use javascript's version of `foreach`
//to check if any of the key value pairs have an empty or null value
for (let key in state){
if(state[key] === null || state[key] === ''){
notEmpty = false;
break;
}
}
return notEmpty;
}
答案 2 :(得分:1)
您可以在对象值上使用Array#some()
method:
function functionIWant(obj) {
return !Object.values(obj).some(v => !v || v == '');
}
演示:
function functionIWant(obj) {
return !Object.values(obj).some(v => !v || v == '');
}
const state1 = {
vale1: '',
vale2: '',
vale3: '',
vale4: ''
}
state2 = {
vale1: '21',
vale2: 'a',
vale3: 'f',
vale4: ''
}
state3 = {
vale1: 'fdf',
vale2: 'fgf',
vale3: 'gf',
vale4: 'hg'
}
state4 = {
vale1: '21',
vale2: 'a',
vale3: 'f'
}
console.log(functionIWant(state1))
console.log(functionIWant(state2))
console.log(functionIWant(state3))
console.log(functionIWant(state4))
答案 3 :(得分:1)
您可以执行以下操作创建一个遍历对象属性的函数:
state1 = {
a: '',
b: 'f',
c: ''
}
state2 = {
a: 'd',
b: 'f',
c: 'g'
}
function isValid(state) {
return Object.values(state).every(val => val != '');
}
console.log(isValid(state1));
console.log(isValid(state2));
Object.values //返回数组中的所有对象值。
every // you apply the predicator in all values.