旧线程,但有新方法可以运行等效的isset()
.
ESNext(2019 年 12 月 4 日)
两种新语法使我们能够极大地简化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
* @returns {Boolean} Value is not undefined or null
*/
function isset (accessor) {
try {
// Note we're seeing if the returned value of our function is not
// undefined or null
return accessor() !== undefined && accessor() !== null
} catch (e) {
// And we're able to catch the Error it would normally throw for
// referencing a property of undefined
return false
}
}
NPM 包
这个答案功能isset-php
在 NPM 上作为包提供。该包包含一些改进,例如类型检查和支持多个参数。
npm install --save isset-php
自述文件中提供了完整的文档。
const isset = require('isset-php')
let val = ''
// This will evaluate to true so the text will be printed.
if (isset(() => val)) {
console.log('This val is set so I will print.')
}
解释
PHP
请注意,在 PHP 中,您可以在任何深度引用任何变量 - 即使尝试将非数组作为数组访问也会返回一个简单的true
or 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
JavaScript
在 JavaScript 中,我们没有那种自由;如果我们做同样的事情,我们总是会得到一个错误,因为引擎会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
// Similar to the above but safe from objects overriding `hasOwnProperty`
Object.prototype.hasOwnProperty.call(some.nested.deeper, 'value') // Error
// ^^^^^^ undefined
// Same goes for typeof
typeof some.nested.deeper !== 'undefined' // Error
// ^^^^^^ undefined
还有一些可以快速获得冗余的可行替代方案:
// Wrap everything in try...catch
try {
if (isset(some.nested.deeper)) {
// ...
}
} catch (e) {}
try {
if (some.nested.deeper !== undefined && some.nested.deeper !== null) {
// ...
}
} 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()
哪个有效,但我个人避免
我想我涵盖了很多。我在回答中提出了一些我没有涉及的观点,因为它们 - 尽管相关 - 不是问题的一部分(例如短路)。不过,如果需要,我可以根据需求使用指向一些更技术方面的链接来更新我的答案。
我花了很多时间在这上面,所以希望它可以帮助人们。
感谢您的阅读!