简体   繁体   中英

Write a function using some method that checks if an item in the array is equal to null (JavaScript)

I can't seem to get this test to pass:

hasNull([1, null, 3])

Expected: true but got: false

My function:

function hasNull(arr) {
  return arr.some((item)=>{ item === null }) ? true : false
}

I made it a bit shorter then your solution. If you remove the curly brackets {} from the array function then it will return the value of item === null check other than that it is just undefined that's why it does not pass any value for some() from your array.

Plus one suggestion is ternary operator in this case is useless because Array.prototype.some() returns a boolean already, see the documentation:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

I guess this can work for you with the following one liner:

 const hasNull = arr => arr.some(item => item === null); console.log(hasNull([1, null, 3]));

I hope that helps!

You're missing return statement:

function hasNull(arr) {
  return arr.some((item) => { return item === null })
}

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