配列にキーが存在しているかを確認する方法

Rubyの場合:

hash = {"key1" => "value1", "key2" => "value2"}
if hash.has_key?("key1")
  puts "Key 'key1' exists in the hash"
else
  puts "Key does not exist in hash"
end

Pythonの場合:

dictionary = {"key1": "value1", "key2": "value2"}
if "key1" in dictionary:
    print("Key 'key1' exists in the dictionary")
else:
    print("Key does not exist in dictionary")

JavaScriptの場合:

let object = {key1: 'value1', key2: 'value2'};
if (object.hasOwnProperty('key1')) {
  console.log('The key "key1" exists in the object');
} else {
  console.log('The key does not exist in the object');
}

Javaの場合:

Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");

if(map.containsKey("key1")) {
    System.out.println("Key 'key1' exists in the map");
} else {
    System.out.println("Key does not exist in map");
}

PHPの場合:

$array = array("key1" => "value1", "key2" => "value2");
if (array_key_exists("key1", $array)) {
  echo "Key 'key1' exists in the array";
} else {
  echo "Key does not exist in array";
}

コメント

タイトルとURLをコピーしました