Вековая ветка, но вот новый способ запустить эквивалент isset()
.
Ответ
См. Объяснение ниже. Примечание. Я использую синтаксис StandardJS
Пример использования
// IMPORTANT pass a function to our isset() that returns the value we're
// trying to test(ES6 arrow function)
isset(() => some) // false
// Defining objects
let some = { nested: { value: 'hello' } }
// More tests that never throw an error
isset(() => some) // true
isset(() => some.nested) // true
isset(() => some.nested.value) // true
isset(() => some.nested.deeper.value) // false
// Less compact but still viable except when trying to use `this` context
isset(function () { return some.nested.deeper.value }) // false
Функция ответа
/**
* Checks to see if a value is set.
*
* @param {Function} accessor Function that returns our value
*/
function isset (accessor) {
try {
// Note we're seeing if the returned value of our function is not
// undefined
return typeof accessor() !== 'undefined'
} catch (e) {
// And we're able to catch the Error it would normally throw for
// referencing a property of undefined
return false
}
}
Объяснение
PHP
Обратите внимание, что в PHP вы можете ссылаться на любую переменную на любой глубине - даже пытаясь
доступ к не массиву как к массиву вернет простое true
или false
:
// Referencing an undeclared variable
isset($some); // false
$some = 'hello';
// Declared but has no depth(not an array)
isset($some); // true
isset($some['nested']); // false
$some = ['nested' => 'hello'];
// Declared as an array but not with the depth we're testing for
isset($some['nested']); // true
isset($some['nested']['deeper']); // false
JS
В JavaScript у нас нет этой свободы, мы всегда получим ошибку, если сделаем
то же самое, потому что JS немедленно пытается получить доступ к значению deeper
прежде чем мы сможем обернуть его в нашей isset()
функции, так что ...
// Common pitfall answer(ES6 arrow function)
const isset = (ref) => typeof ref !== 'undefined'
// Same as above
function isset (ref) { return typeof ref !== 'undefined' }
// Referencing an undeclared variable will throw an error, so no luck here
isset(some) // Error: some is not defined
// Defining a simple object with no properties - so we aren't defining
// the property `nested`
let some = {}
// Simple checking if we have a declared variable
isset(some) // true
// Now trying to see if we have a top level property, still valid
isset(some.nested) // false
// But here is where things fall apart: trying to access a deep property
// of a complex object; it will throw an error
isset(some.nested.deeper) // Error: Cannot read property 'deeper' of undefined
// ^^^^^^ undefined
Больше неудачных альтернатив:
// Any way we attempt to access the `deeper` property of `nested` will
// throw an error
some.nested.deeper.hasOwnProperty('value') // Error
// ^^^^^^ undefined
Object.hasOwnProperty('value', some.nested.deeper) // Error
// ^^^^^^ undefined
// Same goes for typeof
typeof some.nested.deeper !== 'undefined' // Error
// ^^^^^^ undefined
И некоторые рабочие альтернативы, которые могут стать избыточными быстро:
// Wrap everything in try...catch
try { isset(some.nested.deeper) } catch (e) {}
try { typeof some.nested.deeper !== 'undefined' } catch (e) {}
// Or by chaining all of the isset which can get long
isset(some) && isset(some.nested) && isset(some.nested.deeper) // false
// ^^^^^^ returns false so the next isset() is never run
Заключение
Все остальные ответы - хотя большинство из них жизнеспособны ...
- Предположим, вы проверяете, не является ли переменная неопределенной,
подходит для некоторых случаев использования, но все равно может выдать ошибку
- Предположим, вы пытаетесь получить доступ только к свойству верхнего уровня, что опять же
штраф за некоторые варианты использования
- Заставить вас использовать менее чем идеальный подход относительно PHP
isset()
например isset(some, 'nested.deeper.value')
- Используйте
eval()
, который работает, но я лично избегаю
Мне кажется, я многое об этом рассказал. В моем ответе есть несколько моментов, которые я
не касайтесь, потому что они - хотя и актуальны - не являются частью
вопрос. При необходимости я могу обновить свой ответ ссылками на некоторые из
больше технических аспектов, основанных на спросе.
Я потратил много времени на это, так что, надеюсь, это поможет людям.
Спасибо за чтение!