// 创建一个 JavaScript 对象作为字典 (Dictionary)
const dictionary = {
"apple": "A fruit that is typically red, green, or yellow.",
"banana": "A long curved fruit which grows in clusters and has a yellow skin and soft sweet flesh when ripe.",
"carrot": "An edible root vegetable that is typically orange in color."
};
// 获取字典中的值
console.log(dictionary["apple"]); // 输出: A fruit that is typically red, green, or yellow.
// 添加新的键值对
dictionary["dog"] = "A domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, and a barking, howling, or whining voice.";
// 检查字典中是否包含某个键
if ("banana" in dictionary) {
console.log("Dictionary contains 'banana'.");
}
// 删除字典中的键值对
delete dictionary["carrot"];
// 遍历字典
for (let key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
console.log(`${key}: ${dictionary[key]}`);
}
}
{} 创建了一个名为 dictionary 的字典,其中键是字符串,值是描述这些键的字符串。dictionary["apple"] 获取键为 "apple" 的值。dictionary["dog"] = "..." 添加了一个新的键值对。in 关键字检查字典中是否包含某个键。delete 关键字删除指定的键值对。for...in 循环遍历字典中的所有键,并使用 hasOwnProperty 方法确保只访问对象自身的属性。上一篇:js 序列化和反序列化
下一篇:js 位运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站