检查是否定义了变量

Contents

输出结果

value is not defined


程式码


JavaScript

if (typeof value !== 'undefined') {
    console.log('value is defined');
} else {
    console.log('value is not defined');
}

PHP

<?php
if (isset($value)) {
  print "value is defined\n";
}
else {
  print "value is not defined\n";
}

Perl

if (defined($value)) {
  print "value is defined\n";
}
else {
  print "value is not defined\n";
}

Python

try:
    value
except NameError:
    print("value is not defined")
else:
    print("value is defined")

Ruby

if defined? value
    puts "value is defined"
else
    puts "value is not defined"
end