Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js dictionary

作者:鱼宝宝睡觉觉   发布日期:2026-07-15   浏览:92

// 创建一个 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]}`);
    }
}

解释说明:

  1. 创建字典:使用对象字面量 {} 创建了一个名为 dictionary 的字典,其中键是字符串,值是描述这些键的字符串。
  2. 获取值:通过 dictionary["apple"] 获取键为 "apple" 的值。
  3. 添加新键值对:通过 dictionary["dog"] = "..." 添加了一个新的键值对。
  4. 检查键是否存在:使用 in 关键字检查字典中是否包含某个键。
  5. 删除键值对:使用 delete 关键字删除指定的键值对。
  6. 遍历字典:使用 for...in 循环遍历字典中的所有键,并使用 hasOwnProperty 方法确保只访问对象自身的属性。

上一篇:js 序列化和反序列化

下一篇:js 位运算符

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站