简体   繁体   中英

“” in line.map(function(){return $(this).val();}).get()

I'm checking if there's any "" value in a elements array like this

"" in line.map(function(){return $(this).val();}).get()

and it is returning false, but when i debug it on browser i get this on array

line.map(function(){return $(this).val();}).get() = ["1", "2", "4", "", "", "", "", "", "3"]

i suppose that this should be returning true right?

i have already tried with .each but i can't return it unless i use a global variable with a return false;

The in operator does not check whether an array contains a value (that would be indexOf or includes ), it enumerates properties on an object. For example:

 const data = ['a', 'b', 'c', 'd', 'e', 'f']; for (f in data) { console.log('gets the index:', f); console.log('gets the value:', data[f]); // <- note the access using f } 

Rather, you should be using find if you need the element or some if you just need to check presence:

 const data = ['a', 'b', 'c', 'd', 'e', 'f']; console.log('find an element by value:', data.find(it => it === 'c')); console.log('check if any elements match:', data.some(it => it === 'c')); 

You should be using a filter, and checking the length

var hasEmpty = line.filter(function(){ return $(this).val().trim() === ""}).length > 0;

or a little more ES2015, using Array.some on a jQuery collection

var hasEmpty = line.toArray().some((el) => $(el).val() === "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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